You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A nullish coalescing operator, which is essentially an alternative to || that will only return the right-side expression if the left-side is null or undefined (|| returns the right-side if the left-side is falsy, i.e. null | undefined | "" | 0 | false | NaN).
Use Cases
This would be extremely useful anywhere where defaults are needed for potentially omitted inputs, but empty strings or 0, and so forth, are valid inputs that shouldn't be defaulted. My particular use case is AngularJS component bindings. Whenever bindings are updated, I would like to provide a default for a string or boolean binding only when they are straight up omitted (undefined), but I have to do a full-fledged ternary expression with typeof to handle the falsy input corner-case.
In conjunction with the safe chaining operator (#16), handling optionals would be trivial.
Examples
exportinterfaceConfiguration{// Default: "(no name)"; empty string IS validname?: string;// Default: -1; 0 is validitems?: number;// Default: trueactive?: boolean;}functionconfigureSomething(config: Configuration){// With null-coalescing operatorconfig.name=config.name??"(no name)";config.items=config.items??-1;config.active=config.active??true;// Current solutionconfig.name=typeofconfig.name==="string" ? config.name : "(no name)";config.items=typeofconfig.items==="number" ? config.items : -1;config.active=typeofconfig.active==="boolean" ? config.active : true;// Using || operator (INCORRECT)config.name=config.name||"(no name)";// does not allow for "" inputconfig.items=config.items||-1;// does not allow for 0 inputconfig.active=config.active||true;// really bad, always true}
Checklist
My suggestion meets these guidelines:
This wouldn't be a breaking change in existing TypeScript / JavaScript code
This wouldn't change the runtime behavior of existing JavaScript code
This could be implemented without emitting different JS based on the types of the expressions
This isn't a runtime feature (e.g. new expression-level syntax)
ArthaTi, aal89, sahilanguralla, davidje13, TheSimpleZ and 116 moreStef16Robbe and VityaSchelExE-Boss, nisimjoseph, miao17game, vdpdev, gillminister and 8 moreExE-Boss, miao17game, saeedtabrizi, vdpdev, ziishaned and 9 morerafaelim, niedzielski, ExE-Boss, miao17game, saeedtabrizi and 6 moreWesSouza, KevinTCoughlin, niedzielski, vdpdev and brolnickij