typescript

Typescript - Types vs Interface

Gagandeep Singh
Types A type helps in defining the shape or structure of the javascript value. A type can consist of a single property or method or can have combination of multiple properties and methods. For example, the type of variables below can be inferred by typescript by checking the values assigned to them. let id = 123; //number let name = "Gagandeep Singh"; //string let skills = ["typescript", "react"]; // string[] But in case of an object or complex data structure it’s good to define a type beforehand.

Typescript - Union vs Intersection types

Gagandeep Singh
Union Types Multiple types can be defined on a value by using the | symbol. When a value is expected to have one of many known types, then using union type is the most suitable option (rather than any or unknown). type value = number | boolean; Here value can be either number or boolean. We can also combine custom type using the union operator. interface house { hasDoor: boolean; address: string; } interface building { hasLift: boolean; address: string; } type houseOrBuilding = house | building const hb: houseOrBuilding In above case hb can only access members that are common to all types in the union.

Generics in Typescript

Gagandeep Singh
Tuples is a type that exists in Typescript which is similar to Array type but has fixed length and defined what kind of element (either same or different types) will be there at a certain position. // Array example const a: number[] = [1, 2, 3]; // Tuple example const t: [string, number, boolean] = ["2", 1, true]; Since Tuples are just arrays, so it will allow to push a new element only of type either string or number as defined in the tupleType below.

Tuples in Typescript

Gagandeep Singh
Tuples is a type that exists in Typescript which is similar to Array type but has fixed length and defined what kind of element (either same or different types) will be there at a certain position. // Array example const a: number[] = [1, 2, 3]; // Tuple example const t: [string, number, boolean] = ["2", 1, true]; Since Tuples are just arrays, so it will allow to push a new element only of type either string or number as defined in the TupleType below.