[WIP]typescript get started

created: 2021/11/19

 

https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html

Types by Inference
   
Defining Types
Interface

 

interface Name {
    prop1: type1;
    prop2: type2;
    ...
}

 

 ● apply

: TypeName

 

 ● with class

interface SampleInterface {}
Class SampleClass {}
let a: SampleInterface = new SampleClass(...);

 

 

● annotate parameters and return values to functions

function name(p1: Type1, p2: Type2, ....): RType {}

 

 

 

primitive types  
js boolean, bigint, null, number, string, symbol, undefined
ts all above + any, unknown, never, void

 

 

   
Unions
 
type MyBool = true | false;
type WindowStates = "open" | "closed" | "minimized";
type LockStates = "locked" | "unlocked";
type PositiveOddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;

function getLength(obj: string | string[]) {
  return obj.length;
}

 

 

 

 

establish types

 

 type predicate
 string

 

typeof string === "string"

 

 

 number

 

typeof n === "number"

 

 

 boolean

 

typeof b === "boolean"

 

 

 undefined

 

typeof undefined === "undefined"

 

 

 function

 

typeof f === "function"

 

 

 array

 

Array.isArray(a)

 

 

   

 

   
   
   
   
Generics
 such as array

 

type StringArray = Array<string>;
type NumberArray = Array<number>;
type ObjectWithNameArray = Array<{ name: string }>;

 

 

declaration

 

interface Backpack<Type> {
  add: (obj: Type) => void;
  get: () => Type;
}

 

 

   
   
   
   
Structual Type Systems
   If the object or class has all the required properties, TypeScript will say they match, regardless of the implementation details.
   
   
   
   
   
posted @ 2021-11-19 16:25  懒虫哥哥  阅读(30)  评论(0编辑  收藏  举报