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.
This is a proposed feature in TypeScript, under the legendary Issue #16
It won't be introduced into TypeScript until the ECMAScript spec for this feature is firm as there is a desire for the TypeScript implementation to follow that specification - so you'll get it early, but not massively early in this case.
It is referred to as any of the following:
- Null Propagation Operator
- Existential Operator
- Null Coalesce Operator
Update in 2020: The nullish-coalescing operator mentioned below is now through the process and in ES2020, as is the optional chaining operator that lets you do:
let postal_code = address?.postal_code;
// −−−−−−−−−−−−−−−−−−−−−−^
With optional chaining, if address is null or undefined, postal_code will get undefined as its value. But if address is neither null nor undefined, postal_code will get the value of address.postal_code.
JavaScript doesn't have a null-coalescing operator (nor does TypeScript, which mostly limits itself to adding a type layer and adopting features that are reasonably far along the path to making it into JavaScript). There is a proposal for a JavaScript null-coalescing operator, but it's only at Stage 1 of the process.
Using the && idiom you've described is a fairly common approach:
let postal_code = address && address.postal_code;
If address is null (or any other falsy¹ value), postal_code will be that same value; otherwise, it will be whatever value address.postal_code was.
¹ The falsy values are 0, "", NaN, null, undefined, and of course false.
TypeScript types are only enforced at compile time and do not exist at runtime. Given this, if I define a TypeScript function that accepts a string parameter, is it necessary to perform null checks? This question arises because if the API returns null, it could lead to runtime errors.
Consider the following code snippet:
const capitalise = (val: string) => {
// Question: Is this check redundant due to TypeScript's type checking?
if (!val) {
return '';
}
return val.toUpperCase();
};
// Assume 'name' is fetched from an API or another source that could return null
const name: string = /* fetch from API or another source */;
capitalise(name);What are the best practices in such scenarios to ensure runtime safety in TypeScript applications?
Hi, I have a question that I can't seem to find an answer to, but I assume there is an easy fix for?
I have the following code in a .tsx file (as part of the render method):
<div>
<TableHead />
{this.state.scoreList === null ? <CircularProgress /> :
this.state.scoreList.map((row: IScore) => {
<TableRow>
<TableCell>{row.name}</TableCell>
<TableCell>{row.likes}</TableCell>
<TableCell>{row.likesSum}</TableCell>
<TableCell>{row.lps}</TableCell>
</TableRow>
})
}
</div>This throws Type error: Object is possibly 'null'. TS2531 on the 4th line of the snippet, even though - logically - it can't be null because I have caught that with the ternary operator. Is there a way to tell TS this without globally disabling strictNullChecks?
Edit: Thanks all, you guys and gals are amazing, I think I learned like 10 new things just by posting this question, very much appreciated! Sincere props (see what I did there?) to all of you!
I'm coming at this as a typescript beginner and haven't had a deep dive into the docs. So apologies if I'm missing something very obvious.
During development specifically, I feel like I'm adding null checks to my code too early to make TS happy, and this makes it harder to reason about my code. It'll go like this:
-
I perform an operation on a variable that can be null sometimes
-
TS alerts me to this, so I add a null check with an elvis operator/ternary/if
-
The variable is in fact null in an unexpected scenario, so I have a functional error in my app
-
Because I'm null-checking to shush the compiler, I don't immediately know where the bad value originates from and have to dig around for it
I can imagine this getting very annoying once I'm several layers of calls deep. So, how do I think about this? Should I be checking for null values differently? Should I always be doing something in the control flow to indicate an unexpected null was passed? Should I be throwing more?
Advice welcome. Thanks!
Why do you want to use the "non-null assertion operator"?
The status property can either be string | undefined.
What about passing an empty string or perhaps assigning a default value when you don't want to specify a value for status?
<Items status={status || ''}/>
Or:
type ItemProps = {
status?: string;
};
const Items: React.FC<ItemProps> = ({ status = 'statusDefaultValue' }) => <div>Some JSX</div>
It's a bit hard for me to understand your case without knowing the context. Hope this can help.
You can try to use the nullish coalescing operator (??) instead of a logical or (||), as it is a safer operator as some might prefer, like the following:
<Items status={status ?? ''}/>