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.
xis definitely undefined at that point becauseletis a block-scoped variable. you'll need to usevarifxis to be defined in a parent block too.