1. 程式人生 > >typescript 型別對映 (ReadOnly、Partial)

typescript 型別對映 (ReadOnly、Partial)

應用特點

有時候需要一個型別,是依賴於上一個型別但是,對屬性的要求去不同

interface Person{
    name: string;
    agent: number;
}
type Person2 = Readonly<Person>;
type Person3 = Partial<Person>;
class Test {
    run() {
        let person: Person = {
            name: 'dd',
            agent: 1
        };
        person.name = 'cc';
        let person2: Person2 = {
            name: 'read',
            agent: 1
        };
        // person2.agent = 3; 報錯
        let person3: Person3 = {
            name: 'person 3' // 屬性不完整也不會報錯
        }
    }
}

ReadOnly、Partial原始碼

type Readonly<T> = {
    readonly [P in keyof T]: T[P];
}
type Partial<T> = {
    [P in keyof T]?: T[P];
}

ddd

其實這些主要在定義是靈活應用 in, keyof即可實現


type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
}
type Record<K extends string, T> = {
    [P in K]: T;
}