Home > Software engineering >  instantiated object can not find method defined in a function in typescript
instantiated object can not find method defined in a function in typescript

Time:08-14

I define a class Chalk in TypeScript, and some methods defined in the function, like this:

class Chalk{

   public init(): void {

     for (let color of ['black', 'blue', 'cyan', 'gray', 'green', 'magenta', 'red', 'white', 'yellow']) {
       
          this[color] = () => {consol.log(color)}
         }
     }
};

chalk = new Chalk();

but I can't access them from the instantiated object of Chalk when I try to execute:

chalk.red();

The editor tells me that chalk has no 'red' attribute, so what should I do to gain access?

CodePudding user response:

A better approach is to have Colorful interface and make Chalk implement it:

interface Colorful {
  colors: { [key: string]: () => void }
}

class Chalk implements Colorful {
  colors: { [key: string]: () => void }={};
  constructor() {
    for (let color of ['black', 'blue', 'cyan', 'gray', 'green', 'magenta', 'red', 'white', 'yellow']) {
      this.colors[color] = () => { console.log(color) }
    }
  }
};

let chalk = new Chalk();
chalk.colors.green();

Here is a Link to playground

  • Related