Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

?. operator for safe member access #1303

Closed
kevinbarabash opened this issue Nov 29, 2014 · 5 comments
Closed

?. operator for safe member access #1303

kevinbarabash opened this issue Nov 29, 2014 · 5 comments
Labels
Duplicate An existing issue was already created

Comments

@kevinbarabash
Copy link

One of the new features in C# 6 is the new ?. operator which lets you avoid writing lots of boilerplate code when accessing nested properties. It would be nice if there was something similar in TypeScript. http://blogs.msdn.com/b/jerrynixon/archive/2014/02/26/at-last-c-is-getting-sometimes-called-the-safe-navigation-operator.aspx

Problem:

var g1 = null; 
var item = this.parent; 
if (item !== null && item !== undefined) { 
    item = item.child; 
    if (item !== null && item !== undefined) { 
        item = item.child; 
        if (item !== null && item !== undefined) { 
            g1 = item.child; 
        } 
    } 
} 
if (g1 !== null) {
    // do stuff
}

Proposed solution:

var g1 = this.parent?.child?.child?.child;
if (g1 !== null) {
   // do stuff
}

This should also work with the results of method calls and array indexing:

var hrefLength = nodeList.item(0)?.getAttribute("href")?.length;
userList[0]?.firstName = "player 1";
@Eyas
Copy link
Contributor

Eyas commented Nov 29, 2014

#16 is tracking the safe navigation / existential operator. It still is in the "needs proposal" phase.

@kevinbarabash
Copy link
Author

Cool. I'll close this.

@DanielRosenwasser DanielRosenwasser added Duplicate An existing issue was already created Suggestion An idea for TypeScript labels Dec 8, 2014
@SrHuevo
Copy link

SrHuevo commented Apr 15, 2017

please please please hahahahaha

@championswimmer
Copy link

+1 for this. really needed.
#LookAtKotlin

@thomasmost
Copy link

Please!

@RyanCavanaugh RyanCavanaugh removed the Suggestion An idea for TypeScript label Feb 27, 2018
@microsoft microsoft locked as resolved and limited conversation to collaborators Feb 27, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

7 participants