类型数组的Typescript接口 [英] Typescript interface from array type

查看:106
本文介绍了类型数组的Typescript接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要强制数组具有一组特定的值,这些值应该是我接口的键.我可以用

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接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆