const declaration conditional
Allow a const or let declaration in the guard of a conditional.
This shortens the code for trying to obtain some value, checking it is not undefined, and doing something with it.
It reduces the scope of the variable to just the body of the conditional, where it is known to be defined: the human reader knows the variable won't be used sneakily later in the function.
if (const m = /foo/.exec(text)) {
// do something with m
}
// m is out of scope here
This corresponds to
{
const m = /foo/.exec(text);
if (m) {
// β¦
}
}
Also makes sense in the guard for a while loop.
function nextTask(): Task | undefined { β¦ }
β¦
while (const task = nextTask()) {
// Do something with task
}
// task out of scope here
The variable is redeclared for each iteration of the loop so it makes sense for it to be introduced with const not let. The latter would make sense if you want to change it s value inside the body.
My suggestion meets these guidelines:
I wish for this to be supported in JavaScript all the time, but unfortunately:
This feature would agree with the rest of TypeScript's Design Goals.
It doesn't:
- Avoid adding expression-level syntax.
TypeScript only adds expression-level syntax if it becomes ECMAScript standard (Stage 3 or higher).
This should be taken up with es-discuss / TC39. We're not in charge of adding new ways to declare variables in new places.
OK that makes sense -- I can see that it is just as applicable to future ECMAScript as future TypeScript. Thanks.
Most helpful comment
I wish for this to be supported in JavaScript all the time, but unfortunately:
It doesn't:
TypeScript only adds expression-level syntax if it becomes ECMAScript standard (Stage 3 or higher).