来自数组类型的 Typescript 接口

Jul*_*ulo 5 arrays types interface typescript

我需要强制一个数组具有一组特定的值,这些值应该是我的界面的键。我可以强制使用数组

type SomeProperties = ['prop1', 'prop2', 'prop3'];
Run Code Online (Sandbox Code Playgroud)

但我不知道如何强制接口具有这些属性。我试过类似的东西

type MyInterface = {
  [key in keyof SomeProperties]: string;
}
Run Code Online (Sandbox Code Playgroud)

但显然数组的键只是数字,所以我的界面变成了

interface MyInterface {
  0: string;
  1: string;
  2: string;
}
Run Code Online (Sandbox Code Playgroud)

而不是想要的界面

interface MyInterface {
  prop1: string;
  prop2: string;
  prop3: string;
}
Run Code Online (Sandbox Code Playgroud)

你知道是否有办法在 Typescript 中实现这一点?

这会很有用,因为我需要迭代某些属性来“克隆”一个对象,而且我还需要轻松访问这些属性。在类型和接口中重复属性对我来说有点脆弱。

jca*_*alz 7

正如您所注意到的,您尝试访问的字符串不是的SomeProperties,而是的元素SomeProperties

您可以在此处使用索引访问运算符:如果K是 的键(或键的并集)T,则是与访问的键T[K]对应的属性类型(或属性类型的并集)。KT

元组和数组接受number作为键类型,因此您想使用SomeProperties[number]它来提供 union "prop1"|"prop2"|"prop3"

type SomeProperties = ['prop1', 'prop2', 'prop3'];

type MyInterface = {
  [K in SomeProperties[number]]: string;
}

const myInterface: MyInterface = {
  prop1: 'this',
  prop2: 'works',
  prop3: 'now'
}
Run Code Online (Sandbox Code Playgroud)

Playground 代码链接


Mad*_*iha 6

值得注意的是:您不能在 TypeScript 中迭代元组类型

其实你可以!从 TypeScript 3.1 开始,您可以安全地在映射类型(如对象)中使用元组类型

这些操作只能应用于types,不能应用于interfaces。

type SomeProperties = 'prop1' | 'prop2' | 'prop3';

type MyType = Record<SomeProperties, string>;

// equivalent to
// type MyType = {
//   [key in SomeProperties]: string
// }
Run Code Online (Sandbox Code Playgroud)

从消费者的角度来看,类型和接口是相同的(当您要求 a 时MyType,您不在乎它是接口还是类型,在这一点上它们是相同的)