小编Jul*_*ulo的帖子

来自数组类型的 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 中实现这一点?

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

arrays types interface typescript

5
推荐指数
2
解决办法
2869
查看次数

标签 统计

arrays ×1

interface ×1

types ×1

typescript ×1