Typescript類型體操 - PartialByKeys

題目

中文

實現一個通用的PartialByKeys<T, K>,它接收兩個類型參數TK

K指定應設置爲可選的T的屬性集。當沒有提供K時,它就和普通的Partial<T>一樣使所有屬性都是可選的。

例如:

interface User {
    name: string;
    age: number;
    address: string;
}
type UserPartialName = PartialByKeys<User, 'name'>; // { name?:string; age:number; address:string }

English

Implement a generic PartialByKeys<T, K> which takes two type argument T and K.

K specify the set of properties of T that should set to be optional. When K is not provided, it should make all properties optional just like the normal Partial<T>.

For example

interface User {
    name: string;
    age: number;
    address: string;
}
type UserPartialName = PartialByKeys<User, 'name'>; // { name?:string; age:number; address:string }

答案

type PartialByKeys<
    T,
    K extends keyof T | string = keyof T,
    H = { [P in Exclude<keyof T, K>]: T[P] } & {
        [P in K extends keyof T ? K : never]?: T[P];
    }
> = { [K in keyof H as [H[K]] extends [never] ? never : K]: H[K] };

在線演示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章