【问题标题】:Typescript interface from array type来自数组类型的打字稿接口
【发布时间】:2018-01-18 08:20:01
【问题描述】:

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

强制数组
type SomeProperties = ['prop1', 'prop2', 'prop3'];

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

type MyInterface = {
  [key in keyof SomeProperties]: string;
}

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

interface MyInterface {
  0: string;
  1: string;
  2: string;
}

而不是想要的界面

interface MyInterface {
  prop1: string;
  prop2: string;
  prop3: string;
}

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

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

【问题讨论】:

  • 尝试将keyof SomeProperties 更改为SomeProperties[number]
  • @jcalz 这是个好主意,但不幸的是它不起作用,IDE 提示我属性,如 lengthatcharAt 等等,但不是 prop1prop2prop3 :(
  • 不是keyof SomeProperties[number];只是SomeProperties[number]
  • @jcalz 有用,谢谢!如果您创建答案,我可以接受它作为最佳答案

标签: arrays typescript types interface


【解决方案1】:

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

其实可以!自 TypeScript 3.1 you can safely use tuple types in mapped types like objects.

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

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

type MyType = Record<SomeProperties, string>;

// equivalent to
// type MyType = {
//   [key in SomeProperties]: string
// }

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

【讨论】:

  • 我将使用类型更改我的问题,对不起。那么你认为实现我的要求是不可能的吗?
  • 我认为这是一个更好的选择,除非您正在处理数组,例如对于泛型: const ATTACK = "attack"; const CARRY = "携带"; const CLAIM = "索赔";常量工作=“工作”; type EnumDictionary = { [K in Enum]: TValue }; const CREEP_BODY_PART_COST: EnumDictionary = { attack: 80, // OK carry: 50, // OK claim: 600, // OK work: 100 // FAIL };
  • @DropBearDan Screeps FTW!
【解决方案2】:

如您所见,您尝试访问的字符串不是SomeProperties,而是SomeProperties元素

您可以在此处使用indexed access operator:如果KT 的键(或键的联合),则T[K] 是访问对应的属性类型(或属性类型的联合) KT 的密钥。

元组和数组接受number作为键类型,所以你想用SomeProperties[number]给你联合"prop1"|"prop2"|"prop3"

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

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

const myInterface: MyInterface = {
  prop1: 'this',
  prop2: 'works',
  prop3: 'now'
}

希望有所帮助;祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-15
    • 2017-09-26
    • 2020-05-09
    • 2021-07-02
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 2017-09-16
    相关资源
    最近更新 更多