首页 > 解决方案 > 我可以从 Typescript 中的类型中提取可选属性吗?

问题描述

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

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

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

type ExtractOptionalProperties<T> = ??

标签: typescript

解决方案


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>

这应该可以让我知道


推荐阅读