Does Typescript support the ?. operator? (And, what's it called?)

typescript safe navigation operator
typescript optional chaining
typescript elvis operator
typescript nullable
typescript non-null assertion operator
typescript null conditional operator
typescript spread operator
typescript new operator

Does Typescript currently (or are there plans to) support the safe navigation operator of ?.

ie:

var thing = foo?.bar
// same as:
var thing = (foo) ? foo.bar : null;

Also, is there a more common name for this operator (it's incedibly hard to google for).

Update: it is supported as of TypeScript 3.7 and called Optional chaining: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining

I can't find any reference to it whatsoever in the TypeScript language specification.

As far as what to call this operator in CoffeeScript, it's called the existential operator (specifically, the "accessor variant" of the existential operator).

From CoffeeScript's documentation on Operators:

The accessor variant of the existential operator ?. can be used to soak up null references in a chain of properties. Use it instead of the dot accessor . in cases where the base value may be null or undefined.

So, the accessor variant of the existential operator appears to be the proper way to refer to this operator; and TypeScript does not currently appear to support it (although others have expressed a desire for this functionality).

TypeScript Operators, false , it checks the second value. If it's true , it returns true and if it's false , it returns false . An operator defines some function that will be performed on the data. The data on which operators work are called operands. Consider the following expression − 7 + 5 = 12. Here, the values 7, 5, and 12 are operands, while + and = are operators. The major operators in TypeScript can be classified as − Arithmetic operators; Logical operators

Not as nice as a single ?, but it works:

var thing = foo && foo.bar || null;

You can use as many && as you like:

var thing = foo && foo.bar && foo.bar.check && foo.bar.check.x || null;

Spread Operator In TypeScript, Type guards for dotted names also work with user defined type guard functions and the typeof and instanceof operators and do not depend on the --  Since TypeScript also uses angle brackets for type assertions, combining it with JSX’s syntax would introduce certain parsing difficulties. As a result, TypeScript disallows angle bracket type assertions in .tsx files. Since the above syntax cannot be used in .tsx files, an alternate type assertion operator should be used: as.

This is defined in the ECMAScript Optional Chaining specification, so we should probably refer to optional chaining when we discuss this. Likely implementation:

const result = a?.b?.c;

The long and short of this one is that the TypeScript team are waiting for the ECMAScript specification to get tightened up, so their implementation can be non-breaking in the future. If they implemented something now, it would end up needing major changes if ECMAScript redefine their specification.

See Optional Chaining Specification

Where something is never going to be standard JavaScript, the TypeScript team can implement as they see fit, but for future ECMAScript additions, they want to preserve semantics even if they give early access, as they have for so many other features.

Short Cuts

So all of JavaScripts funky operators are available, including the type conversions such as...

var n: number = +myString; // convert to number
var b: bool = !!myString; // convert to bool
Manual Solution

But back to the question. I have an obtuse example of how you can do a similar thing in JavaScript (and therefore TypeScript) although I'm definitely not suggesting it is a graceful as the feature you are really after.

(foo||{}).bar;

So if foo is undefined the result is undefined and if foo is defined and has a property named bar that has a value, the result is that value.

I put an example on JSFiddle.

This looks quite sketchy for longer examples.

var postCode = ((person||{}).address||{}).postcode;
Chain Function

If you are desperate for a shorter version while the specification is still up in the air, I use this method in some cases. It evaluates the expression and returns a default if the chain can't be satisfied or ends up null/undefined (note the != is important here, we don't want to use !== as we want a bit of positive juggling here).

function chain<T>(exp: () => T, d: T) {
    try {
        let val = exp();
        if (val != null) {
            return val;
        }
    } catch { }
    return d;
}

let obj1: { a?: { b?: string }} = {
    a: {
        b: 'c'
    }
};

// 'c'
console.log(chain(() => obj1.a.b, 'Nothing'));

obj1 = {
    a: {}
};

// 'Nothing'
console.log(chain(() => obj1.a.b, 'Nothing'));

obj1 = {};

// 'Nothing'
console.log(chain(() => obj1.a.b, 'Nothing'));

obj1 = null;

// 'Nothing'
console.log(chain(() => obj1.a.b, 'Nothing'));

What does the construct x = x || y mean?, The null elimination is pretty obvious here, but you can use terser operators too: ts subtle and, besides, --strictNullChecks does not always work with old code. The TypeScript team announced the release of TypeScript 3.7, including optional chaining, nullish coalescing, assertion functions, and numerous other developer ergonomic improvements.

Update: Yes its supported now!

It just got released with TypeScript 3.7 : https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/

It is called optional chaining : https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/#optional-chaining

With it the following:

let x = foo?.bar.baz(); 

is equivalent to:

let x = (foo === null || foo === undefined) ?
    undefined :
    foo.bar.baz();
Old answer

There is an open feature request for this on github where you can voice your opinion / desire : https://github.com/Microsoft/TypeScript/issues/16

`null` vs. `undefined` in TypeScript land - BASARAT, This extension does two things: it enables JSX inside of TypeScript files, and it makes the any ambiguity between JSX expressions and the TypeScript prefix cast operator). To use JSX-support with React you should use the React typings. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more In Typescript, what is the !

Edit Nov. 13, 2019!

As of November 5, 2019 TypeScript 3.7 has shipped and it now supports ?. the optional chaining operator 🎉🎉🍾🍾🎉!!!

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining


For Historical Purposes Only:

Edit: I have updated the answer thanks to fracz comment.

TypeScript 2.0 released !. It's not the same as ?.(Safe Navigator in C#)

See this answer for more details:

https://stackoverflow.com/a/38875179/1057052

This will only tell the compiler that the value is not null or undefined. This will not check if the value is null or undefined.

TypeScript Non-null assertion operator

// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
    // Throw exception if e is null or invalid entity
}

function processEntity(e?: Entity) {
    validateEntity(e);
    let s = e!.name;  // Assert that e is non-null and access name
}

TypeScript 3.7 · TypeScript, I think whoever claims dibs first can put up a draft PR and then hopefully work with others to contribute fixes, finish things out, and add testcases. @​sheetalkamat  @benjaminz I don't see how it could be handled by a boolean. Typescript needs to know that the function into which you pass an object is functioning like a type guard. If it just returns type true or false, how can Typescript know that it's indeed a type guard and not just some arbitrary function that returns true if the object is truthy.

TypeScript 2.0 · TypeScript, Spoiler alert: Optional chaining and the null coalescing operator are in the JavaScript/TypeScript world is continuously checking variables or  I just start to learn TypeScript, and I saw there is a lot of code using this sytax =>. I did some research by reading the Specification of TypeScript Version 1.6 and some googling.

Handbook - Advanced Types, We're pleased to announce TypeScript 3.7 Beta, a feature-complete version of TypeScript 3.7. You can also get editor support by The star of the show in optional chaining is the new ?. operator for optional property  History. TypeScript was first made public in October 2012 (at version 0.8), after two years of internal development at Microsoft. Soon after the announcement, Miguel de Icaza praised the language itself, but criticized the lack of mature IDE support apart from Microsoft Visual Studio, which was not available on Linux and OS X at that time.

TypeScript 1.6 · TypeScript, Does Typescript support the ?. operator? (And, what's it called?) typescript operator typescript elvis operator typescript non-null assertion operator typescript​  Optional Chaining operator. The optional chaining operator helps you write expressions that stops running as soon as null or undefined is encountered.. For example you can refactor your code like this if you want to check that user is not null or undefined:

Comments
  • @mattytommo you do have that in c#, its called the null coalescing operator and uses the ?? syntax weblogs.asp.net/scottgu/archive/2007/09/20/…
  • @BasaratAli Unfortunately not, coalesce is fine for property ?? property2, but if you tried property.company ?? property1.company and property was null, you'd get a NullReferenceException
  • @mattytommo Thanks I get it now '?.' actually soaks all null references in the chain. Sweet.
  • @mattytommo this does exist now for C#: msdn.microsoft.com/en-us/library/dn986595.aspx
  • The Microsoft rep that visited us called it the Elvis operator as the question mark looks like Elvis' hair and a microphone he is singing into...
  • "accessor variant of the existential operator". Naturally. So catchy, it's near impossible to forget. :). Thanks for the extremely thorough answer.
  • @MartyPitt Sure thing! I agree, I'd love to see a) wider adoption of an operator like this (C# please!) and b) a better name (the "safe navigation" operator from your linked blog post has a nice ring to it).
  • Angular implements this in it's templates: angular.io/guide/…
  • In some other languages its called the "Elvis" operator
  • It's announced for TypeScript 3.7.0 (github.com/microsoft/TypeScript/issues/…)
  • && evaluates as long as the statement is true. If it is true, it returns the last value. If it is false, it returns the first value that evaluated to false. That may be 0, null, false etc. || returns the first value that evaluates to true.