簡體   English   中英

在“typeof Object”類型上找不到帶有“string”類型參數的索引簽名

[英]No index signature with a parameter of type 'string' was found on type 'typeof Object'

我做了一個類似 enum 的課程: 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類的列表。

問題似乎是使用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]);

我希望這可以幫到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM