typescript进阶篇之高级类型与条件类型(Readonly, Partial, Pick, Record)

本文所有东西尽可在 typescript 官网文档寻找,但是深浅不一

高级类型

lib 库中的五个高级类型
以下所有例子皆以 person 为例

interface Person {
    name: string;
    age?: number;
}

Partial

源码:

type Partial = {
    [P in keyof T]?: T[P];
};

实例:

type person2 = Partial;
// person2 === {name?: string; age?: number}

Required

源码:

type Required = {
    [P in keyof T]-?: T[P];
};

实例:

type person3 = Required;
// person3 === {name: string; age: number}

Readonly

源码:

type Readonly = {
    readonly [P in keyof T]: T[P];
};

实例:

type person4 = Readonly;
// person4 === {
//        readonly name: string;
//        readonly age?: number;
//  }

Pick

源码:

type Pick = {
    [P in K]: T[P];
};

实例:

type person5 = Pick;
// person5 === {name: string}

Record

源码:

type Record = {
    [P in K]: T;
};

实例:

type person6 = Record<'name' | 'age', string>
// person6 === {name: string; age: string}

条件类型

关于条件类型,官网上说的很详细了,我就直接拿过来

type T00 = Exclude<"a" | "b" | "c" | "d", "a" | "c" | "f">;  // "b" | "d"
type T01 = Extract<"a" | "b" | "c" | "d", "a" | "c" | "f">;  // "a" | "c"

type T02 = Exclude void), Function>;  // string | number
type T03 = Extract void), Function>;  // () => void

type T04 = NonNullable;  // string | number
type T05 = NonNullable<(() => string) | string[] | null | undefined>;  // (() => string) | string[]

function f1(s: string) {
    return { a: 1, b: s };
}

class C {
    x = 0;
    y = 0;
}

type T10 = ReturnType<() => string>;  // string
type T11 = ReturnType<(s: string) => void>;  // void
type T12 = ReturnType<(() => T)>;  // {}
type T13 = ReturnType<(() => T)>;  // number[]
type T14 = ReturnType;  // { a: number, b: string }
type T15 = ReturnType;  // any
type T16 = ReturnType;  // any
type T17 = ReturnType;  // Error
type T18 = ReturnType;  // Error

type T20 = InstanceType;  // C
type T21 = InstanceType;  // any
type T22 = InstanceType;  // any
type T23 = InstanceType;  // Error
type T24 = InstanceType;  // Error

高级类型与条件类型就这些,如果能够掌握他们,你就能在 ts 的海洋中任意遨游了

你可能感兴趣的:(typescript,前端)