【问题标题】:Typescript how get optional keys of type [duplicate]打字稿如何获取类型的可选键[重复]
【发布时间】:2018-12-17 23:16:31
【问题描述】:

有一种类型

{ a: string, b: number, c?: string, d?: number }

如何获取类型

'c' | 'd'

从此?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    终于找到了基于Typescript how to create type with common properties of two types?的解决方案

    type MappedC<A, B> = {
      [K in keyof A & keyof B]:
      A[K] extends B[K]
        ? never
        : K
    };
    
    type OptionalKeys<T> = MappedC<T, Required<T>>[keyof T];
    

    但它的工作原理很神奇,因为当将这两种类型合二为一并将 B 替换为 Required 时,它会停止工作。

    其他解决方案,似乎更稳定:

    export type KeysOfType<T, U> = { [K in keyof T]: T[K] extends U ? K : never }[keyof T];
    export type RequiredKeys<T> = Exclude<KeysOfType<T, Exclude<T[keyof T], undefined>>, undefined>;
    export type OptionalKeys<T> = Exclude<keyof T, RequiredKeys<T>>;
    

    【讨论】:

    • 这些实际上是不同的解决方案。例如:ts type Foo = { a: string; b: string | undefined; c?: string }; 前一个解决方案(基于Mapped)将返回(预期):'c'。后一种解决方案(基于RequiredKeys)将返回(意外):'b' | 'c'
    猜你喜欢
    • 2021-03-19
    • 2018-10-17
    • 1970-01-01
    • 2022-06-13
    • 2022-01-25
    • 2021-01-22
    • 2019-05-04
    • 2020-05-09
    • 2022-11-02
    相关资源
    最近更新 更多