【问题标题】:TypeScript: enforcing a single dynamic key on an objectTypeScript:在对象上强制执行单个动态键
【发布时间】:2019-07-02 09:21:31
【问题描述】:

有没有办法为具有单个动态命名键的对象编写接口?

我能够编写一个接受任意数量的动态命名键的接口,但我想将其限制为一个。

让我们从一些基础开始,然后逐步解决我的问题。在以下界面中,对象只能有一个键,并且命名为“id”:

interface Test {
  id: string
}

这很好,因为具有此接口的对象只能具有一个属性,id。但我需要消费者能够指定此键的名称。

如果我将该接口更改为以下,它允许消费者指定自定义键:

type Test<K extends string> = {
  [P in K]: string
}

这让我更接近我正在寻找的东西,正如我们在这个例子中看到的那样:

type SpecificTest = Test<"customId">;

const test:SpecificTest = {
  customId: 'pls',
}

但是,用户可以传递联合类型来定义多个 ID 字段,这就是问题所在。

// I don't want a user to be able to pass multiple strings here
type SpecificTest = Test<"customId"|"anotherId">;

const test:SpecificTest = {
  customId: 'pls',

  // :(
  anotherId: 'blah'
}

我在想这些方面的东西可能会奏效(在伪代码中):

type Test<K extends string> = {
  [K]: string
}

但是那个特定的语法不起作用。

有没有办法定义一个用户只能定义一个单个动态命名键的界面?

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    可以通过IsUnionhelper type 来检测传入的类型是否为union

    type Test<K extends string> = IsUnion<K> extends true ? Error<'Please don\'t pass a union'>  : {
      [P in K]: string
    }
    
    interface Error<M> {msg: M}
    

    【讨论】:

    • 这很好用!太感谢了!我很快就会接受这个答案。
    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 2019-07-11
    • 2017-08-10
    • 2021-10-05
    相关资源
    最近更新 更多