typescript - 我可以从 Typescript 中的类型中提取可选属性吗?
问题描述
我想知道是否有一种方法可以仅提取在给定类型中定义为可选的属性。
type MyType = {
a: number,
optional1?: number,
optional2?: number,
}
// Should be { optional1?: number, optional2?: number }
type OptionalPropertiesOfMyType = ExtractOptionalProperties<T>;
type ExtractOptionalProperties<T> = ??
解决方案
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>
这应该可以让我知道
推荐阅读
- ruby-on-rails - 在 Rails 控制器中检查 JSON 响应中的值
- sapui5 - 如何在 sapui5 文本或输入框中放置换行符?
- javascript - 来自 CORS 预检通道的 CORS 标头“Access-Control-Allow-Headers”中缺少令牌
- jquery - jQuery 选择页面重定向
- nativescript - 如何在 Nativescript 中将 base64 图像转换为 blob 或 dataURL
- reactjs - react-native-image-progress 的图片标签
- c# - C# 获取 xml 文件的 CDATA 中的节点
- ruby - 如何在 Ruby 中使用唯一的硬件 ID 保护我的代码?
- python - keras 自定义函数不会评估/编译/拟合
- sql - 如何选择和计算每个唯一行的最频繁的第一个值?