Declare local variable as optional
See original GitHub issueEvery time I type an undefinable variable, I think I typed something wrong:
let a: string | undefined;
Why do I think I did something wrong? It’s because I never add undefined
type to a union type as above except in variable declarations.
Don’t you think it is time, introduce the optional operator to local variable declarations as well?
let a?: string;
The above syntax feel very natural and idiomatic typescript for me.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:188
- Comments:8 (2 by maintainers)
Top Results From Across the Web
Documentation - Variable Declaration - TypeScript
When a variable is declared using let , it uses what some call lexical-scoping or block-scoping. Unlike variables declared with var whose scopes...
Read more >Is using 'var' to declare variables optional? - javascript
"Optional" is perhaps an unfortunate choice of words, as var is optional in the sense that an assignment statement can be successfully interpreted...
Read more >Implicitly typed local variables - C# Programming Guide
Local variables can be declared without giving an explicit type. ... In many cases the use of var is optional and is just...
Read more >SQL Server Declare, Set and Select Variable - Guru99
By default, DECLARE initializes variable to NULL. Using the keyword 'AS' is optional. To declare more than one local variable, use a comma ......
Read more >Declare a Local Variable Anywhere Within the Source Code
When you assign a value to the local variable while you declare it, declaring the data type is optional. The data type of...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I just tried using
let s? : string = null;
and failed miserably. lolGuess till it is done
let s: string | null;
has to suffice. But voting forlet s? : string = null;
please.Regards.
While this is an old issue I just thought I’d leave a note here in case anyone else finds this. A lot of libraries make this optional syntax nicer using generics. For example, defining Maybe as
type Maybe<T> = T | null;
which then lets you do things like
let foo: Maybe<string> = null;
It’s not really saving on characters but I think it reads nicer. Could also do something liketype Nullish<T> = T | null | undefined;
and
type Opt<T> = T | undefined;