【问题标题】:How create TS interface with dynamic key?如何使用动态密钥创建 TS 接口?
【发布时间】:2021-05-11 11:43:03
【问题描述】:

keyArray = [key1, key2, key3,...] //this is dynamic value array.

我想使用 keyArray 创建如下图所示的 TS 接口。

interface = {
  key1 : string;
  key2 : string;
  key3 : string;
  ...
}

我该怎么做?

【问题讨论】:

  • 不清楚你的意思 - 类型只存在于编译时,它们在运行时被删除(因为没有输入 JavaScript)。

标签: javascript typescript dynamic interface


【解决方案1】:

很难做到这一点,因为这取决于变量key1 等的类型。

我们可以通过(typeof keyArray)[number]获取keyArray的值的类型,我们可以创建一个类型,以这些类型作为键,string作为值:

type FromKeys = Record<(typeof keyArray)[number], string>

但键类型是key1type 等——而不是value。如果key1 的类型是字符串文字,这正是您想要的。但是如果key1 的类型只是string,那么您的FromKeys 类型将允许任何string 属性并且不会特别有用。

type FromKeys<T extends readonly PropertyKey[]> = Record<T[number], string>

declare function makeObject<T extends readonly PropertyKey[]>(keyArray: T): FromKeys<T>;

const obj1 = makeObject(["a", "b", "c"]); // Record<string, string>
const obj2 = makeObject(["a", "b", "c"] as const); // Record<"a" | "b" | "c", string>

Playground Link

【讨论】:

    猜你喜欢
    • 2018-03-23
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 2012-02-06
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多