【发布时间】: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