类型数组的Typescript接口

编程入门 行业动态 更新时间:2024-10-23 04:51:10
本文介绍了类型数组的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接口

本文发布于:2023-05-29 23:10:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/355114.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   接口   类型   Typescript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!