Initialize variable with Typescript defined interface

Asked

Viewed 124 times

0

I’m dealing with Angular and maintaining an older version code. Currently, when we need to define the parameters of an object in Typescript, we use an interface:

export interface RetornoEstatisticaAvaliacao {
  QuantidadeDetrator: number
  QuantidadeNeutro: number
  QuantidadePromotor: number
  PorcentagemDetrator: number
  PorcentagemNeutro: number
  PorcentagemPromotor: number
  ValorNps: number
}

Which used to be used as a class for type definition, so in the past we were able to initialize a variable simply by instantiating this class:

estatisticaNps: RetornoEstatisticaAvaliacao = new RetornoEstatisticaAvaliacao();

As she is no longer a class, rather a interface, it generates a variable startup error:

RetornoEstatisticaAvaliacao only refers to a type, but is being used as value at the moment.

What is the right way to initialize this variable with defined type?

  • 1

    You cannot instantiate a type (as you are doing now). What you can do is create a class that implements the type RetornoEstatisticaAvaliacao, so that it is possible to instantiate this class you have created. Remember that any type is deleted in Runtime and therefore it is not possible to use them as if they were part of the Javascript code issued by tsc.

  • So the problem is exactly this because the old code did this instance and today as I changed from class to interface I can’t instantiate anymore. Then I need to initialize the variable in some way that I don’t know how.

  • Just create a class that implements the interface Feedback. See how to do

  • So the question is, why did you switch from class to interface? If you have a good reason, then there is no way, you need to create a class that implements it. If you have no reason, undo the change...

  • Pq the programmer before me created the class only to define the type ai I had to make this change by following a more current model

1 answer

-2


estatisticaNps: RetornoEstatisticaAvaliacao = {QuantidadeDetrator: 0...}

Only start properties directly

  • The way is to do it anyway and is even a good practice: statistics { Percentage Value: 0, Value: 0, Quantity Tractor: 0, Quantity Other: 0, Quantity Value: 0, Percentage Value: 0, };

Browser other questions tagged

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