Home > OS >  Accessing object property when object consists of classes
Accessing object property when object consists of classes

Time:02-21

With an object consisting of references to classes:

// commands/index.ts
export default {
  Authorize,
  BootNotification,
  ...
  UpdateFirmware,
};

How do I go about creating variables and instantiate dynamically from this object? For something like bellow I get the ts error:

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.

Code:

import commands from "./commands"; 
let commandNameOrPayload: typeof commands;
let commandPayload: any;
let CommandModel: typeof commands;

CommandModel = commands[commandNameOrPayload];
commandRequest = new CommandModel(commandPayload);

For the last line of newCommandModel I'm getting the error: TS2351: This expression is not constructable.

CodePudding user response:

The classes from your commands export are indexed by the string representation of their name, so in order to access them, your commandNameOrPayload also needs to be of 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)

See my playground: https://tsplay.dev/wjkrbN

  • Related