如何使用另一种类型的可选键创建一个类型并使它们成为必需的?

问题描述 投票:0回答:1

假设我有以下类型:

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]>
}

有两个问题:

  1. 不通用
  2. VSCode/NVim 将其键显示为
    (property) timeout: NonNullable<number | boolean | undefined>
    而不是
    (property) timeout: number | boolean
typescript
1个回答
0
投票

我会选择这个...选择所有可选道具并使用

-?

将它们设置为必需

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>

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.