Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a variable if undefined in typescript?

Tags:

typescript

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;
like image 363
Rahul Dagli Avatar asked Nov 16 '17 11:11

Rahul Dagli


People also ask

Can you set a value to undefined in TypeScript?

YES, you can, because undefined is defined as undefined.

How do you define an undefined variable in TypeScript?

To make a variable null we must assign null value to it as by default in typescript unassigned values are termed undefined. We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.

How do you handle undefined in TypeScript?

TypeScript has a powerful system to deal with null or undefined values. By default null and undefined handling is disabled, and can be enabled by setting strictNullChecks to true.

How do you set a undefined variable?

To set the value of a variable is it's equal to undefined , use the nullish coalescing operator, e.g. myVar = myVar ?? 'new value' . The operator returns the right-hand side operand if the left-hand side evaluates to undefined or null , otherwise it returns the left-hand side operand. Copied!


1 Answers

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

x ??= default_value
like image 141
mcoolive Avatar answered Oct 15 '22 14:10

mcoolive