3

我做了一个类似枚举的类:https ://stackoverflow.com/a/51398471

export default class Juice
{
  [key: string]: any;

  static APPLE = new Juice('APPLE', 'Apple juice');
  static ORANGE = new Juice('ORANGE', 'Orange juice');

  private constructor(private key:string, public readonly text:string) {
  };
}

当我使用我定义的密钥访问时,它工作正常,但是当我尝试像这样动态访问时它失败了:

console.log(Juice.APPLE); //works fine
console.log(Juice['APPLE']); //works fine
const key = 'APPLE'; //works fine
console.log(Juice[key]); //works fine
console.log(Object.keys(Juice).map((key:string) => Juice[key])); // error!

错误是:

TypeScript error in `path`
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof Juice'.
No index signature with a parameter of type 'string' was found on type 'typeof Juice'.  TS7053

有没有人帮助我错误的原因是什么以及解决方案?

请帮忙,谢谢。

我在课堂上添加了索引签名,但没有帮助

[key: string]: any;
export default class Juice
{
  [key: string]: any;

  static APPLE = new Juice('APPLE', 'Apple juice');
  static ORANGE = new Juice('ORANGE', 'Orange juice');

  private constructor(private key:string, public readonly text:string) {
  };
}

获取enum班级列表。

4

1 回答 1

1

该问题似乎正在使用Object.keys,因为它始终会遍历字符串列表与作为对象键的字符串列表。如果你想获取一个对象的所有值,我会改用Object.values. 然而,这将导致一个问题,因为构造函数也将作为一个值(原型)返回,这将导致其他类型问题。

我建议将您的静态果汁作为一个单独的对象,您可以在需要时引用。例子:

class Juice {
  constructor(private key: string, public readonly text: string) {}
}

const juices = {
  APPLE: new Juice('APPLE', 'Apple juice'),
  ORANGE: new Juice('ORANGE', 'Orange juice')
};
export default juices;

console.log(Object.values(Juice));

const test: keyof typeof juices = 'APPLE';
console.log(juices[test]);

我希望这可以帮到你。

于 2019-07-09T04:14:18.593 回答