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>]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM