typescript类型体操_partialbykeys_laggage-编程思维

题目

中文

实现一个通用的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] };

在线演示

版权声明:本文版权归作者所有,遵循 CC 4.0 BY-SA 许可协议, 转载请注明原文链接
https://www.cnblogs.com/laggage/p/type-challenge-partial-by-keys.html