Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

239
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda