我需要强制数组具有一组特定的值,这些值应该是我接口的键.我可以用
I need to force an array to have a specific set of values that should be then the keys of my interface. I can force the array with
type SomeProperties = ['prop1', 'prop2', 'prop3'];但是我不知道如何强制接口具有这些属性.我尝试过类似的
but I don't know how to force an interface to have those properties. I tried something like
type MyInterface = { [key in keyof SomeProperties]: string; }但是很明显,数组的键只是数字,所以我的界面变成了
but obviously the keys of an array are just numbers so my interface become
interface MyInterface { 0: string; 1: string; 2: string; }代替所需的界面
interface MyInterface { prop1: string; prop2: string; prop3: string; }您知道在Typescript中是否有办法实现这一目标?
Do you know if there is a way to achieve this in Typescript?
这将很有用,因为我需要迭代某些属性以克隆"对象,并且还需要轻松访问这些属性.在类型和接口上重复属性对我来说有点脆弱.
It would be useful because I need to iterate on some properties to "clone" an object and I also need to access to those properties easily. Repeating the properties in both type and interface is a bit fragile for me.
推荐答案您注意到,您尝试访问的字符串不是 SomeProperties 的 keys ,但 SomeProperties 的 elements .
As you note, the strings you're trying to access aren't the keys of SomeProperties, but the elements of SomeProperties.
您可以使用索引访问运算符此处:如果 K 是 T 的键(或键的并集),则 T [K] 是属性类型(或并集属性类型)对应于访问 T 的 K 键.
You can use the indexed access operator here: if K is a key (or a union of keys) of T, then T[K] is the property type (or union of property types) corresponding to accessing the K key(s) of T.
组合和数组接受 number 作为键类型,因此您想使用 SomeProperties [number] 为您提供并集"prop1" |"prop2"|" prop3":
Tuples and arrays accept number as a key type, so you want to use SomeProperties[number] to give you the union "prop1"|"prop2"|"prop3":
type SomeProperties = ['prop1', 'prop2', 'prop3']; type MyInterface = { [key in SomeProperties[number]]: string; } const myInterface: MyInterface = { prop1: 'this', prop2: 'works', prop3: 'now' }希望有所帮助;祝你好运!
Hope that helps; good luck!
更多推荐
类型数组的Typescript接口
发布评论