Reputation: 29993
When creating a TypeScript interface one can make an entry "optional", or type | undefined
, by adding a question mark, eg.
interface Foo {
myProperty?: boolean;
}
Is there a way to do this when declaring a variable? None of the following seems to work:
let myVar?: boolean;
let myVar: boolean?;
let myVar: boolean = undefined;
Upvotes: 2
Views: 2292
Reputation: 250942
can make an entry "optional", or
type | undefined
, by adding a question mark
You can't use the ?
syntax for this with variables.
If you are using strict null checks (strictNullChecks
compiler flag), you can explicitly allow undefined values:
let myVar: boolean | undefined;
Or nulls:
let myVar: boolean | null;
This will prevent the uninitialized variable check that the compiler performs, as shown below.
let myVar: boolean;
if (myVar) { // Hey coder! myVar hasn't been assigned!
console.log('x');
}
If you aren't using strict null checks, the boolean
type would already allow null and undefined with the normal type annotation.
let myVar: boolean;
Upvotes: 4