Using a juggling-check, you can test both null and undefined in one hit:
if (x == null) {
If you use a strict-check, it will only be true for values set to null and won't evaluate as true for undefined variables:
if (x === null) {
You can try this with various values using this example:
var a: number;
var b: number = null;
function check(x, name) {
if (x == null) {
console.log(name + ' == null');
}
if (x === null) {
console.log(name + ' === null');
}
if (typeof x === 'undefined') {
console.log(name + ' is undefined');
}
}
check(a, 'a');
check(b, 'b');
Output
Answer from Fenton on Stack Overflow"a == null"
"a is undefined"
"b == null"
"b === null"
Videos
Using a juggling-check, you can test both null and undefined in one hit:
if (x == null) {
If you use a strict-check, it will only be true for values set to null and won't evaluate as true for undefined variables:
if (x === null) {
You can try this with various values using this example:
var a: number;
var b: number = null;
function check(x, name) {
if (x == null) {
console.log(name + ' == null');
}
if (x === null) {
console.log(name + ' === null');
}
if (typeof x === 'undefined') {
console.log(name + ' is undefined');
}
}
check(a, 'a');
check(b, 'b');
Output
"a == null"
"a is undefined"
"b == null"
"b === null"
if( value ) {
}
will evaluate to true if value is not:
nullundefinedNaN- empty string
'' 0false
typescript includes javascript rules.
Yes. As of TypeScript 3.7 (released on November 5, 2019), this feature is supported and is called Optional Chaining:
At its core, optional chaining lets us write code where TypeScript can immediately stop running some expressions if we run into a
nullorundefined. The star of the show in optional chaining is the new?.operator for optional property accesses.
Refer to the TypeScript 3.7 release notes for more details.
Prior to version 3.7, this was not supported in TypeScript, although it was requested as early as Issue #16 on the TypeScript repo (dating back to 2014).
As far as what to call this operator, there doesn't appear to be a consensus. In addition to "optional chaining" (which is also what it's called in JavaScript and Swift), there are a couple of other examples:
- CoffeeScript refers to it as the existential operator (specifically, the "accessor variant" of the existential operator):
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.
- C# calls this a null-conditional operator.
a null-conditional operator applies a member access,
?., or element access,?[], operation to its operand only if that operand evaluates to non-null; otherwise, it returnsnull.
- Kotlin refers to it as the safe call operator.
There are probably lots of other examples, too.
It is now possible, see answer of user "Donut".
Old answer: Standard JavaScript behaviour regarding boolean operators has something that may help. The boolean methods do not return true or false when comparing objects, but in case of OR the first value that is equal to true.
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;
Default values are also possible:
var name = person && person.name || "Unknown user";
Yes, as of Typescript 3.7 you can now do this via optional-chaining
person?.getName()?.firstName
gets transpiled to
let firstName = person === null || person === void 0 ? void 0 : (_person$getName = person.getName()) === null || _person$getName === void 0 ? void 0 : _person$getName.firstName;
Note the check for null. This will work as expected if for example person is defined as
let person:any = null; //no runtime TypeError when calling person?.getName()
However if person is defined as
let person:any = {};//Uncaught TypeError: person.getName is not a function
See also this similar stackoverflow question
No, as of now safe navigation operatior is still not implemented in Typescript: https://github.com/Microsoft/TypeScript/issues/16
However according to the latest standardization meeting notes it has been proposed, so maybe v3 :)
https://github.com/tc39/agendas/blob/master/2017/07.md
It's called the "Non-null assertion operator" and it tells the compiler that x.getY() is not null.
It's a new typescript 2.0 feature and you can read about it in the what's new page, here's what it says:
A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.
// 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
}
Edit
There's an issue for documenting this feature: Document non-null assertion operator (!)
Non-null assertion operator: !
- You tells the TS compiler that the value of a variable is not
null | undefined - Use it when you are in possession of knowledge that the TS compiler lacks.
Here is a trivial example of what it does:
let nullable1: null | number;
let nullable2: undefined | string;
let foo = nullable1! // type foo: number
let fooz = nullable2! // type fooz: string
It basically removes null | undefined from the type
When do I use this?
Typescript is already pretty good at inferring types for example using typeguards:
let nullable: null | number | undefined;
if (nullable) {
const foo = nullable; // ts can infer that foo: number, since if statements checks this
}
However sometimes we are in a scenario which looks like the following:
type Nullable = null | number | undefined;
let nullable: Nullable;
validate(nullable);
// Here we say to ts compiler:
// I, the programmer have checked this and foo is not null or undefined
const foo = nullable!; // foo: number
function validate(arg: Nullable) {
// normally usually more complex validation logic
// but now for an example
if (!arg) {
throw Error('validation failed')
}
}
My personal advice is to try to avoid this operator whenever possible. Let the compiler do the job of statically checking your code. However there are scenarios especially with vendor code where using this operator is unavoidable.