microsoft / microsoft/TypeScript
Narrowed `const` variables are widened in block-scoped closures
- Langage dominant
- Go
- Étoiles
- 111k
- Forks
- 14.3k
- Merge moyen
- 2 j 4 h
- PR mergées (30 j)
- 132
Description
### 🔎 Search Terms
narrowing, cfa, closure,
### 🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about n/a
### ⏯ Playground Link
https://www.typescriptlang.org/play/?noUncheckedIndexedAccess=true&target=99&ts=5.8.0-dev.20250209#code/CYUwxgNghgTiAEYD2A7AzgF3mgXNjMAligOYDcAUBYQGbwAUa8AvK-AOQ1JLsCU8AbwrwRiVJmwBBCIShNm2SqPg0ArijAZCqeACMowevyHLlydFi5I8nbuxaLhogL5VlajVp0luh409MxCxVuGyt7BTRpWTQlFwpXChAADwAHJBgsAWcgA
### 💻 Code
```ts
declare const s: string;
if (s === 'foo') {
function bad() {
const foo: 'foo' = s;
}
}
// in non-strict code bad() might be accessible outside of the narrowed branch,
// so make sure we're strict
export {}
```
### 🙁 Actual behavior
error trying to use the variable as its narrowed value.
### 🙂 Expected behavior
No error. `bad()` is a local function only reachable within the scope in which `s` has been definitely narrowed to `'foo'`.
### Additional Information
Found organically in https://github.com/typescript-eslint/typescript-eslint/pull/10182#discussion_r1948337564 (with a narrowed member access corollary)
Guide de contribution
Ouvrir le guide de contribution
Piste de recherche
Commencez par la reproduction liée dans TypeScript Playground et l’exemple de code montrant un const affiné dans une fonction à portée de bloc. Suivez la façon dont l’affinement du flux de contrôle est géré pour les déclarations de fonctions locales et vérifiez que l’exemple ne signale plus d’erreur, tout en préservant le comportement de strict-mode décrit dans l’issue.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- typescript
- Domaine
- compilers
- Type d'issue
- Bug
- Difficulté
- 4/5
- Temps estimé
- 3-5 jours
- Activité
- À l'abandon
- Clarté
- Plutôt claire
- Accessibilité débutants
- 45/100