我需要强制一个数组具有一组特定的值,这些值应该成为我的接口中的键。 我可以使用以下方法强制数组:
type SomeProperties = ['prop1', 'prop2', 'prop3'];
但我不知道如何强制接口具有这些属性。我尝试了类似于以下内容的东西:
type MyInterface = {
[key in keyof SomeProperties]: string;
}
但是显然,数组的键只是数字,所以我的接口变成了
interface MyInterface {
0: string;
1: string;
2: string;
}
替代所需要的接口
interface MyInterface {
prop1: string;
prop2: string;
prop3: string;
}
您知道在TypeScript中是否有实现这个功能的方法吗?
这将非常有用,因为我需要迭代一些属性来“克隆”一个对象,并且我还需要轻松地访问这些属性。对于我来说,在类型和接口中重复这些属性有点脆弱。
keyof SomeProperties
更改为SomeProperties[number]
。 - jcalzlength
、at
、charAt
等等,但没有prop1
、prop2
或prop3
:( - Julokeyof SomeProperties[number]
;只是SomeProperties[number]
。 - jcalz