Typescript: Syntax for scoping declaration of constant to conditional that uses it

Created on 5 Jul 2019  Β·  3Comments  Β·  Source: microsoft/TypeScript

Search Terms

const declaration conditional

Suggestion

Allow a const or let declaration in the guard of a conditional.

Use Cases

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.

Examples

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.

Checklist

My suggestion meets these guidelines:

  • [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [x] This wouldn't change the runtime behavior of existing JavaScript code
  • [x] This could be implemented without emitting different JS based on the types of the expressions
  • [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [x] This feature would agree with the rest of TypeScript's Design Goals.
Out of Scope Suggestion

Most helpful comment

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:

  1. Avoid adding expression-level syntax.

TypeScript only adds expression-level syntax if it becomes ECMAScript standard (Stage 3 or higher).

All 3 comments

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:

  1. 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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kyasbal-1994 picture kyasbal-1994  Β·  3Comments

weswigham picture weswigham  Β·  3Comments

zhuravlikjb picture zhuravlikjb  Β·  3Comments

jbondc picture jbondc  Β·  3Comments

siddjain picture siddjain  Β·  3Comments