TypeScript – the most interesting in TS:
1. A fixed length array is commonly called a tuple.
let tuple: [number, number] = [0, 0];
2. Type Alias is used for describing the repeating fields in object –
anything that is used as a type annotation in TS can be given a
name using type alias:
a) It allows to name our intent;
b) It allows to remove code duplication.
type Point = { x: number, y: number };
let center: Point = {
x: 0,
y: 0,
}
let unit: Point = {
x: 1,
y: 1,
}
3. Annotations used for functions in TypeScript:
type Add = (a: number, b: number) => number;
let add: Add;
add = function(a: number, b: number): number {
return a + b;
};
add = (a, b) => a + b;
4. User and Product have the same type compatibility:
this means that you can assign a user to a product or
a product to a user because they have the same structure.
type User = { id: string };
type Product = { id: string };
let user: User = { id: “user-some122” };
let product: Product = { id: “product-some182” };
5. DUCK TYPING!
type Point2D = { x: number, y: number };
type Point3D = { x: number, y: number, z: number };
let point2D: Point2D = { x: 0, y: 10 };
let point3D: Point3D = { x: 0, y: 10, z: 20 };
For TS structural type system the extra information in type is OK.
// Here Extra info is OK:
point2D == point3D;
This means that we can assign a point3D to a point2D because
point3D have all members required by point2D (x and y fields).
Such assignment can happen indirectly, for example this code is OK:
function takesPoind2D(point: Point2D) { … }
takesPoind2D(point3D); // NO ERRORS
This is called Duck typing: when a type Point3D holds all the features required
by Point2D and more but Point2D doesn’t have all the features of Point3D:
it’s missing the property z of type number.
// Error: missing info!
point3D = point2D;
function takesPoind3D(point: Point3D) { … };
takesPoind3D(point2D); // ERROR!!!