Reputation: 4502
I'm trying to set the variable value when it's undefined however, I'm getting an error while trying to use vanilla javascript approach.
Block-scoped variable 'x' used before its declaration.
What is the best approach when using typescript for setting undefined variable?
let x = (typeof x === 'undefined') ? def_val : x;
Upvotes: 30
Views: 71517
Reputation: 250882
TypeScript can tell that x
is definitely not defined, because it is a block-scoped variable and you can see the whole block.
If you know better than the compiler, you can separate the lines:
const def_val = 'default';
let x: string;
x = (typeof x === 'undefined') ? def_val : x;
But you might want to consider how the block scoped variable could possibly be undefined in your case (perhaps your code is not quite as simple as the example in your question).
The common use case would be more like:
const def_val = 'default';
function work(y: string) {
let x = (typeof y === 'undefined') ? def_val : y;
}
You can also add more strict compiler options to make it less likely the value will be undefined in many cases.
There is also a shorthand falsey-coalesce that may be useful:
const def_val = 'default';
function work(y: string) {
let x = y || def_val;
}
This will replace undefined
, null
, 0
(zero) or ''
with the default.
Upvotes: 21
Reputation: 4205
The logical nullish assignment (x ??= y) operator only assigns if x is nullish (null or undefined).
x ??= default_value
Upvotes: 47
Reputation: 765
There is another a shorthand using the Nullish coalescing operator:
const def_val = 'default';
function work(y: string) {
let x = y ?? def_val;
}
This will replace only undefined
or null
with the default.
Upvotes: 18