TypeScript-- advanced type

Cross-type

Union ∪ suitable objects mixed

 

 

// CROSS Type -> 
interface DogInterFace {
    run(): void
}
interface CatInterFace {
    Jump (): void 
} 
// At this point the members of the union have a pet let pet: DogInterFace
& CatInterFace = { run() {}, jump() {} }

 

Union type

Can not determine the type of declaration is one -> intersection enhanced flexibility ∩ code
let a: number | string = 'a';
B the let: 'A' | 'B' | 'C' // literal union type (only one of them can be assigned) 
the let C:. 1 | 2 |. 3
  • Union type object
class Dog implements DogInterFace {
    run() {}
    eat() {}
}
class Cat implements CatInterFace {
    jump() {}
    eat() {}
}
enum Master { Boy, Girl }
function getPet(master: Master) {
    let pet = master === Master.Boy ? new Dog() : new Cat();
    pet.eat () // union type in the undetermined type can be accessed with a membership of all types of 
    return PET
}
Index Type
It can be achieved query and access to object properties
  • Query operator keyof T
interface Obj {
    a: number,
    b: string
}
Key the let: keyof Obj // At this point type "a" | amount literal "b" type
  • Index access operator T [K]
let value: Obj['a'] // number
Mapping Types
One way to create a new type from the old type
type ReadonlyObj = Readonly <Obj> // all members becomes Readonly 
type PartialObj = the Partial <the Obj> // all members become selectable 
type PickObj = of Pick <the Obj, 'A'> // select specific members
 // can reassign members and specifies member type
type RecordObj = Record<'x' | 'y' | 'z',Obj>
Condition Type
One type is determined by the conditional expression
// T extends U ? X : Y
type TypeName<T> = 
  T extends string ? "string" :
  T extends number ? "number" :
  T extends boolean ? "boolean" :
  T extends undefined ? "undefined" :
  T extends Function ? "function" :
  "object";

type T1 = TypeName<string> // string
type T2 = TypeName<string[]> // object
type T3 = TypeName<string | string[]> // string | object

type Diff<T, U> = T extends U ? never : T
type T4 = Diff<'a'|'b','a'> // ’b'
type noNull<T> = Diff<T,null|undefined> // 去除null和undefined

 

 

Guess you like

Origin www.cnblogs.com/JessieXie/p/12272745.html