【问题标题】:Is it possible to create union key value type from object type?是否可以从对象类型创建联合键值类型?
【发布时间】:2018-09-06 08:58:28
【问题描述】:

例如我有对象类型

type FooBar = {
  foo: number,
  bar: string
}

我想创建这种类型

{key: "foo", value: number} | {key: "bar", value: string}

我可以创造

{key: keyof FooBar}

{value: FooBar[keyof FooBar]}

但我想以某种方式将它们结合起来。

【问题讨论】:

  • type FooBar = {key: "foo", value: number} | {key: "bar", value: string}?

标签: typescript mapped-types


【解决方案1】:

您可以使用映射类型来做到这一点。将每个键映射到{key: <keyname>, value: <keytype>} 类型,然后使用keyof 构建所有这些键的联合:

type FooBar = {
  foo: number,
  bar: string
}

type KV<T> = {[K in keyof T]: {key: K, value: T[K]}}[keyof T];

declare const test: KV<FooBar>;
// `test` has type: {key: "foo", value: number} | {key: "bar", value: string}

【讨论】:

    猜你喜欢
    • 2020-02-08
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2020-05-21
    • 2022-08-18
    • 2011-03-11
    • 2021-12-02
    • 2018-08-19
    相关资源
    最近更新 更多