Typescript类型体操 - RequiredByKeys

题目

中文

实现一个通用的RequiredByKeys<T, K>,它接收两个类型参数TK

K指定应设为必选的T的属性集。当没有提供K时,它就和普通的Required<T>一样使所有的属性成为必选的。

例如:

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

English

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

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

For example

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

答案

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

在线演示

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