使用由對類的參考組成的物件:
// commands/index.ts
export default {
Authorize,
BootNotification,
...
UpdateFirmware,
};
如何創建變數并從此物件動態實體化?對于像下面這樣的事情,我得到了 ts 錯誤:
TS2538: Type '{ Authorize: typeof Authorize; BootNotification: typeof BootNotification; CancelReservation: typeof CancelReservation; ChangeAvailability: typeof ChangeAvailability; ... 23 more ...; UpdateFirmware: typeof UpdateFirmware; }' cannot be used as an index type.
代碼:
import commands from "./commands";
let commandNameOrPayload: typeof commands;
let commandPayload: any;
let CommandModel: typeof commands;
CommandModel = commands[commandNameOrPayload];
commandRequest = new CommandModel(commandPayload);
對于newCommandModel我收到錯誤的最后一行:TS2351: This expression is not constructable.
uj5u.com熱心網友回復:
您commands匯出的類由其名稱的字串表示索引,因此為了訪問它們,您commandNameOrPayload還需要是 type string:
class A {/**bla**/}
class B {/**bla**/}
let commands = {
A,
B
}
console.log(commands["A"]) // will log class A {}
let command = new commands["A"];
console.log(command instanceof A)
看看我的游樂場:https ://tsplay.dev/wjkrbN
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/429986.html
