Does TypeScript operator have a null conditional operator

Is there any kind of operator like ?. in TypeScript, which can check if a variable is null or not defined as Kotlin? how

person?.getName()?.firstName ?: "None" 
+5
source share
3 answers

No, at the moment, a safe navigation operation is still not implemented in Typescript: https://github.com/Microsoft/TypeScript/issues/16

However, in accordance with the latest comments about the standardization meeting, this was suggested, so maybe v3 :)

https://github.com/tc39/agendas/blob/master/2017/07.md

+5
source

This is actually related to the security of the javascript null discussion that is mentioned in this answer . I think they want it to be supported in javascript before they get to typescript.

0
source

I faced the same situation and it worked for me.

First, I defined a separate class with a property, which may be null :

 export class Foo { id: number; //this can be null } 

Then, in my main class, I set the foo property for this new type:

 foo: Foo 

After that, I was able to use it as follows:

 var fooId = (this.foo || ({} as Foo)).id; 

This is the closest I could get zero distribution in the current version of TypeScript.

0
source

Source: https://habr.com/ru/post/1270438/


All Articles