假设我有以下类型:
type Props = {
title: string
color?: string
timeout?: number | boolean
}
我想创建一个仅包含
color
和 timeout
但必需的类型,即:
type RProps = RequiredOptional<Props>
导致
type RProps = {
color: string
timeout: number | boolean
}
这可能吗?如何实现?
我找到了关于如何从类型中获取可选键的答案(如this),但没有找到如何做我想做的事情。我得到的最好的是:
type OptionalKeys<T extends object> = keyof {
[K in keyof T as T extends Record<K, T[K]> ? never : K]: K
}
type RProps = {
[key in OptionalKeys<Props>]: NonNullable<Props[key]>
}
有两个问题:
(property) timeout: NonNullable<number | boolean | undefined>
而不是 (property) timeout: number | boolean
我会选择这个...选择所有可选道具并使用
-?
将它们设置为必需
type Props = {
title: string
color?: string
timeout?: number | boolean
}
type OptionalProps<T extends object> = {
[K in keyof T as T extends Record<K, T[K]> ? never : K]-?: T[K]
}
type RProps = OptionalProps<Props>