当对象由 类 组成时访问对象 属性
Accessing object property when object consists of classes
对象包含对 类 的引用:
// 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.
您的 commands
导出的 类 由其名称的字符串表示索引,因此为了访问它们,您的 commandNameOrPayload
也需要是类型 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
对象包含对 类 的引用:
// 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.
您的 commands
导出的 类 由其名称的字符串表示索引,因此为了访问它们,您的 commandNameOrPayload
也需要是类型 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