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

237
Views
define model classes in TypeScript

currently I define my model classes in this way:

export class Company {
  constructor(
    public id?: number,
    public name?: string,
    public shortName?: string
  ) {}
}

The reason, why I use ? is that in this case I don't get an error that values for properties aren't provided if I want to assign an empty company object to a variable like this:

this.editDataItem = new Company();

Can I somehow avoid the use of ? in the model declaration? Or is this the right way if I want to assign an empty instance to a variable without declaring all the properties? Are there any best practices for this?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can also do like this, It is in JS.

class Company {
  constructor(
     id = 0,
     name = '',
     shortName = ''
  ) {}
}

const company1 = new Company();

console.log(company1);

In Typescript you can do this:

export class Company {
  constructor(
    public id: number = 0,
    public name: string = '',
    public shortName: string = ''
  ) {}
}

const company1 = new Company();

console.log(company1);

The above snippet will help you to set the default values even if they are not passed. It could be a better way to achieve this, ? accepts undefined as value.

over 4 years ago · Santiago Trujillo Report

0

The ? is just a shorthand for undefined. To prevent a property being undefined you would need to set it on initialization either by passing values to the constructor or setting default values.

Depending on your use-case this is a perfectly valid and correct way to define a models property types.

You might as well change your class to:

export class Company {
  id?: number;
  name?: string;
  shortName?: string;

  constructor(
  ) {}
}

Now you still have public properties but they are undefined by default and there is no need to pass any values to the constructor.

over 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!