31

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;
1
  • 1
    x is definitely undefined at that point because let is a block-scoped variable. you'll need to use var if x is to be defined in a parent block too. Commented Nov 16, 2017 at 11:53

3 Answers 3

49

The logical nullish assignment (x ??= y) operator only assigns if x is nullish (null or undefined).

x ??= default_value
Sign up to request clarification or add additional context in comments.

1 Comment

This is what I was looking for!
21

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.

Shorthand

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.

2 Comments

Wish I had known about y || def_val earlier. So much annoying duplication in my code lol
@takanuva15 in my experience, if you feel like you need to duplicate your code / do other nasty things, there is probably some language feature / syntax sugar for that exact situation
18

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.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.