映射类型不能声明属性或方法 - TypeScript

问题描述 投票:0回答:2

我有一个接口,它应该具有特定枚举键类型的键,但是当我声明该类型时,它给出了此错误:

映射类型不能声明属性或方法。

这是代码:

enum myEnum {
  propOne = 'propOne',
  propTwo = 'propTwo'
}

export interface myInterface {
  [key in myEnum]: anotherInterface;
}

我也尝试像这样指定类型,但它不起作用并给了我语法错误:

export interface myInterface {
  [key in keyof typeof myEnum]: anotherInterface;
}

我也尝试使用普通对象而不是枚举,但它给出了相同的错误。

javascript typescript enums
2个回答
78
投票

您需要使用映射类型,而不是接口:

export type MyInterface = {
  [key in myEnum]: AnotherInterface;
}


0
投票

扩展映射类型:

type MyMappedType = {
  [key in myEnum]: AnotherInterface;
}

interface MyInterface extends MyMappedType {
  field: string,
  field2: string
}
© www.soinside.com 2019 - 2024. All rights reserved.