TypeScript类型映射

ts可以使用泛型来做类型映射,将对象或数组中类型转换为另一个类型。

例如:

定义一个类型

interface Student{
    name: string,
    age: number
}

1. 把一个类型的每个属性都变为可空的

type Nullable<T> = {
    [p in keyof T]: T[P] | null
}

type NullableStudent = Nullable<Student>

2. 把一个类型的每个属性都变为只读的

//定义readonly映射
type Readonly<T> = {
    readonly [P in keyof T]: T[P]
}

type ReadonlyStudent = Readonly<Student>

3. 把一个类型的属性都变为可选的

type Partical<T> = {
    [P in keyof T]?: T[P]
}

type ParticalStudent = Partical<Student>

4. 把一个类型的每个项都变为Promise

//定义toPromise映射
type ToPromise<T> = { [K in keyof T]: Promise<T[K]> };

type Coordinate = [number, number]

type PromiseCoordinate = ToPromise<Coordinate>; // [Promise<number>, Promise<number>]