Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

216
Views
instantiated object can not find method defined in a function in typescript

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?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!