Problem checking if a type any is Undefined in Typescript

Asked

Viewed 165 times

2

I am having a problem checking if a variable is Undefined in the following typescript code.

Atendimento:any;

this.Atendimento.Checkout.Observacao == undefined ? '' : this.Atendimento.Checkout.Observacao;

If the Call does not return anything from the webservice, therefore setting the Call to Undefined, the following code gives error saying that the variable this.Atendimento.Checkout.Note is Undefined, ignoring the if, someone would know how to solve(Without having to declare a model class, because doing so would be a hassle in the system) and why this problem occurs?

  • Is there any way to check this in an if?

  • Peter using Any in Typescript on many occasions is considered a bad practice, just as in this case you have an object that contains another object that contains some properties, the ideal would be to have all nodes typed to avoid the feared Undefined and not have to stay making If knot by knot as in the example of our friend Rodrigo.

  • If I’m not mistaken, it’s possible to use something like this.?Atendimento.Checkout.Observacao but I can’t remember how it works

3 answers

1


You can check each node.

this.Atendimento == undefined || this.Atendimento.Checkout == undefined || this.Atendimento.Checkout.Observacao == undefined ? '' : this.Atendimento.Checkout.Observacao;

  • I thought you had a smaller code to make these validations, but thanks, it helped a lot.

0

If you’re not instantiating your variable inside some ctor, just do it. If Webservice ensures that Object Checkout is instantiated, you will not need any more checks other than whether the observations are empty or of value.

this.Atendimento === undefined ? alert("null") : alert("instanciado");

Example here

0

Probably what’s going on is that this.Atendimento.Checkout is Undefined, so when trying to access the attribute "Note" the error is triggered. Do multiple validations like in Rodrigo Costa’s answer.

Browser other questions tagged

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