Conditional

Basic usage

Condition types are similar to the ternary operators in JS, i.e

SomeType extends OtherType ? TrueType : FalseType;
Copy the code
  • Basic use:
interface Animal { live(): void; } interface Dog extends Animal { woof(): void; } type Example1 = Dog extends Animal ? number : string; //type Example1 = number type Example2 = RegExp extends Animal ? number : string; //type Example2 = stringCopy the code

Extents is defined as follows: A extends B means that type A can be assigned to type B, rather than that type A inherits from type B, which is true if A has A smaller scope than B

type Duck = { name: string; } type Cat = { name: string; } type Bool1 = Duck extends Cat ? 'yes' : 'no'; // Bool1 => 'yes' // Duck type can be assigned to Cat, so 'yes' type Human = {name: string; occupation: string; } type Bool2 = Human extends Duck ? 'yes' : 'no'; // Bool2 => 'yes' type Bool3 => Duck extends Human? 'yes' : 'no'; // Bool3 => 'no' type Bool4 = never extends Human ? 'yes' : 'no'; // Bool4 => 'yes' //never specialsCopy the code

extends

Extends in TS has two other uses in addition to conditional types: inheritance and generic constraints

  • inheritance
​
// Dog => { name: string; bark(): void }
interface Animal {
    kind: string;
}
interface Dog extends Animal {
  bark(): void;
}
Copy the code
  • Generic constraint

    When writing generics, we can restrict the type parameters, for example, we want to pass in an array of parameters with the name attribute:

Function getCnames<T extends {name: string}>(entities: entities) T[]):string[] { return entities.map(entity => entity.name) }Copy the code

Infer usage

Represents a type variable to be inferred in the extends condition statement. Simple example:

type ParamType<T> = T extends (... args: infer P) => any ? P : T;Copy the code

If the following two ways of writing mean the same thing,

Type Flatten<T> = T extends any[]? T[number] : T; Infer: type Flatten< type > = type extends Array<infer Item>? Item : Type;Copy the code