有没有办法为具有以下属性的对象编写接口single动态命名的键?
我能够编写一个接受任意数量的动态命名键的接口,但我想将其限制为只有一个。
让我们从一些基础知识开始,然后逐步解决我的问题。在下面的接口中,对象只能有一个键,并且它被命名为“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
}
但该特定语法不起作用。
有没有办法定义一个用户只能定义一个接口single动态命名的键?