Monday, June 15, 2020

Types in TypeScript

1. Object vs object

Object represents alll types in typescript include all primitive type and non-primitive type.

primitivie type has the following types:
  • boolean
  • number
  • biginit
  • string
  • symbol
  • null :means absence of a value
  • undefined : variable that has not been defined.
in contrast object represent non-primitive type.

we can define a object with property, optional property and index signature.

let exampleO :{
      p1: string,
      p2?: number //optional property
     [p3: string]: string //index singatue [key:T] : U to indicate all keys of T(T should be number and string only) must have values of type U
}

Typescript use index signature to add more keys to the object.

2. Array vs Tuples

both types use square bracket []

let a: string[] //declare a string array

let b: [string] //a tuple

let c: [string, string, number] // a tuple with three elements

3. use const enum to prevent the unsafe access

enum Color {
     Red,
     White,
    Green
}
we should rewrite it with const enum for a safer subset of enum behavior, since CONST ENUMS doesn't let you do reverse looks up. However number value enums still will allow all numbers assign to enums, we can avoid this issue with string-value enums

const enum Color {
     Red,
     White,
    Green
}


No comments:

Post a Comment