Initialize object with defined type without specifying each value

Asked

Viewed 72 times

-1

I would like to initialize an object without setting each value in Typescript

Let’s simulate a simple situation where we have the Car Object:

export interface Carro {
      QuantidadePortas: number,
      Marca: string,
      Modelo: number,
      AnoFabricacao: number
    }

To initialize the object before filling it with the appropriate information I am obliged to define each value:

carroSelecionado: Carro = {QuantidadePortas: 0, Marca: '', Modelo: 0, AnoFabricacao: 0000};

But when I have large objects with more than 20/30 values makes it too difficult.

Here comes the question, is there any way to make this boot easier?

Show 1 more comment

2 answers

0

In Typescript we have the values declared mandatory and not mandatory, for example:

QuantidadePortas: number

It’s a mandatory attribute. To make it optional, you must put ? before :, in this way:

QuantidadePortas?: number
  • I removed the "hi, all right?", understand the reason by reading here: https://pt.meta.stackoverflow.com/q/846/112052

-1

Thank you for the comment of Rafael Tavares who has the answer here at Stackoverflow and solved my problem.

I adopted this pattern to initialize objects

carroSelecionado = {} as Carro;
  • 1

    By doing this you are circumventing Typescript checks. This can cause you problems, since Typescript will say that the object has already been declared with all due properties

  • In this case Typescript will not check the type when associating a valid response to the object?

  • If you do let carroSelecionado = {} as Carro; and try carroSelecionado.QuantidadePortas, will receive undefined without Typescript complaining (which is wrong). Later associate a valid object to carroSelecionado, will be able to access the properties normally.

  • Then the right one would even define an initial value for each property?

  • The answer you mentioned has the options you can use. Or use Partial<Carro> or defined the properties in the declaration.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.