我可以从Typescript中的类型中提取可选属性吗?

时间:2019-07-04 06:54:20

标签: typescript

我想知道是否有一种方法可以只提取在给定类型中定义为可选的属性。

type MyType = {
a: number,
optional1?: number,
optional2?: number,
}

// Should be { optional1?: number, optional2?: number }
type OptionalPropertiesOfMyType = ExtractOptionalProperties<T>;

type ExtractOptionalProperties<T> = ??

1 个答案:

答案 0 :(得分:2)

type MyType = {
a: number,
optional1?: number,
optional2?: number,
}


type UndefinedKeys<T> = {
    [K in keyof T]: undefined extends T[K] ? K : never;
}[keyof T]

type ExtractOptional<T> = Pick<T, Exclude<UndefinedKeys<T>, undefined>>


type Test = ExtractOptional<MyType>

这应该让我知道