Home > Enterprise >  define model classes in TypeScript
define model classes in TypeScript

Time:09-30

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?

CodePudding user response:

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.

CodePudding user response:

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.

  • Related