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

177
Views
How to rewrite class to plain object?

How would one rewrite this class to a plain object?

class ExampleClass {
    firstPropery: number = 0;
    secondProperty!: string;

  async exampleMethod(): Promise<void> {
    const { secondProperty } = await SomeHelperClass.exampleRequest();
    this.secondProperty = secondProperty;
  }
}

I would think it's something similar as this

interface IExample {
  firstProperty: number;
  secondProperty: string;
  exampleMethod: () => Promise<void>;
}

const Example: IExample = {
  firstProperty: 0,
  exampleMethod: async (): Promise<void> => {
    const { secondProperty } = await SomeHelperClass.exampleRequest();
    ...
  }
}

But how to set the secondProperty via the exampleMethod? In the class method I can just write this.secondProperty = ..., which I cannot do in the plain object.

My second question is, with the class I would make a new object like this const newObject = new ExampleClass();. With the plain object way, how would I make a new object instance?

Any help is gladly appreciated!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

In the class method I can just write this.secondProperty = ..., which I cannot do in the plain object.

Actually you can. It doesn't matter whether it's defined in a class or object literal, exampleMethod is still a method and when called as example.exampleMethod() it will have its this point to example. However, you cannot use an arrow function to define it - use method syntax instead:

const example: IExample = {
  firstProperty: 0,
  async exampleMethod(): Promise<void> {
    const { secondProperty } = await SomeHelperClass.exampleRequest();
    ...
  }
}

With the class I would make a new object like this const newObject = new ExampleClass();. With the plain object way, how would I make a new object instance?

You write the code again and again. Or you use Object.assign to copy the method onto a new object. Or you place the object literal inside a function that you can call multiple times.

about 4 years ago · Juan Pablo Isaza 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!