玩转TypeScript工具类型（中）

2021/09/15 18:30

• 必读：extends 条件运算符

• Exclude<Type, ExcludeUnion>

• Extract<Type, Union>

• NonNullable<Type>

• 必读：tuple type 元组类型

• Parameters<Type>

• ConstructorParameters<Type>

• ReturnType<Type>

• InstanceType<Type>

youdao

ydtech

[译]TypeScript条件类型：https://juejin.cn/post/6985463429502877726

youdao

ydtech

2.1

type Exclude<T, U> = T extends U ? never : T;

2.2

// 排除一个具体的值type T0 = Exclude<"a" | "b" | "c", "a"> // "b" | "c"// 排除一种类型type T1 = Exclude<string | number | (() => void), Function>

T0 为例，extends 关键字是如何发挥作用的呢？

type T0 = Exclude<"a" | "b" | "c", "a"> // "b" | "c"// 等价于type T0 = "a" extends "a" ? never : "a"   | "b" extends "a" ? never : "b"  | "c" extends "a" ? never : "c"// 等价于type T0 = never | "b" | "c"// 等价于type T0 = "b" | "c"

[译]TypeScript条件类型 ：https://juejin.cn/post/6985463429502877726

youdao

ydtech

3.1

/** * Extract from T those types that are assignable to U */type Extract<T, U> = T extends U ? T : never;

3.2

// 提取一个具体的值type T0 = Extract<"a" | "b" | "c", "a"> // "a" // 提取一种类型type T1 = Extract<string | number | (() => void), Function>

youdao

ydtech

4.1

源码解析

type NonNullable<T> = T extends null | undefined ? never : T

4.2

type T0 = NonNullable<string | number | undefined>;// type T0 = string | numbertype T1 = NonNullable<string[] | null | undefined>;// type T1 = string[]

youdao

ydtech

Tuple types allow you to express an array with a fixed number of elements whose types are known, but need not be the same.

let x: [string, number];

// OKconsole.log(x[0].substring(1));// Property 'substring' does not exist on type 'number'.console.log(x[1].substring(1));

let x: [string, number];x = ["hello", 10]; // OK// Type '"world"' is not assignable to type 'undefined'.// Tuple type '[string, number]' of length '2' has no element at index '3'.x[3] = "world";// Object is possibly 'undefined'.// Tuple type '[string, number]' of length '2' has no element at index '5'.console.log(x[5].toString());

youdao

ydtech

6.1

/** * Obtain the parameters of a function type in a tuple */type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;

• T extends (...args: any) => any，规定了 T 必须是一个函数（any和never 除外），参数是 any 类型，所以参数可以是任意类型

• T extends (...args: infer P) => any ? P : never，如果T是函数类型，那么这个 extends 走的就是 true 分支，也就是返回一个 P类型，而这个 P 类型就是参数 args 的类型

[译]TypeScript条件类型：https://juejin.cn/post/6985463429502877726

6.2

declare function f1(arg: { a: number; b: string }): void;type T0 = Parameters<() => string>;// type T0 = []type T1 = Parameters<(s: string) => void>;// type T1 = [s: string]type T2 = Parameters<<T>(arg: T) => T>;// type T2 = [arg: unknown]type T3 = Parameters<typeof f1>;// type T3 = [arg: { a: number; b: string; }]type T4 = Parameters<any>;// type T4 = unknown[]type T5 = Parameters<never>;// type T5 = nevertype T6 = Parameters<string>;// Type 'string' does not satisfy the constraint '(...args: any) => any'.type T7 = Parameters<Function>;// Type 'Function' does not satisfy the constraint '(...args: any) => any'.// Type 'Function' provides no match for the signature '(...args: any): any'.

youdao

ydtech

7.1

/** * Obtain the parameters of a constructor function type in a tuple */type ConstructorParameters<T extends abstract new (...args: any) => any> = T extends abstract new (...args: infer P) => any ? P : never;

• abstract关键字修饰的函数叫抽象方法，而抽象方法只能出现在抽象类中

• new (...args: any) => any，这就是对构造函数的定义

7.2

interface ErrorConstructor {  new(message?: string): Error;  (message?: string): Error;  readonly prototype: Error;}type T0 = ConstructorParameters<ErrorConstructor>;

type T0 = string

youdao

ydtech

8.1

/** * Obtain the return type of a function type */type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;

8.2

declare function f1(): { a: number; b: string };type T0 = ReturnType<() => string>;// type T0 = stringtype T1 = ReturnType<(s: string) => void>;// type T1 = voidtype T2 = ReturnType<<T>() => T>;// type T2 = unknowntype T3 = ReturnType<<T extends U, U extends number[]>() => T>;// type T3 = number[]type T4 = ReturnType<typeof f1>;// type T4 = {a: number;b: string;}type T5 = ReturnType<any>;// type T5 = anytype T6 = ReturnType<never>;// type T6 = nevertype T7 = ReturnType<string>;// 类型“string”不满足约束“(...args: any) => any”。ts(2344)type T8 = ReturnType<Function>;// 类型“Function”不满足约束“(...args: any) => any”。// 类型“Function”提供的内容与签名“(...args: any): any”不匹配。ts(2344)

youdao

ydtech

9.1

/** * Obtain the return type of a constructor function type */type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any;

9.2

interface FunctionConstructor {  /**   * Creates a new function.   * @param args A list of arguments the function accepts.   */  new(...args: string[]): Function;  (...args: string[]): Function;  readonly prototype: Function;}type T0 = InstanceType<FunctionConstructor>;

type T0 = Function;

youdao

ydtech

• ThisParameterType<Type>

• OmitThisParameter<Type>

• ThisType<Type>

0 评论
3 收藏
1