microsoft / microsoft/TypeScript
Narrowed `const` variables are widened in block-scoped closures
- Ngôn ngữ chính
- Go
- Star
- 111k
- Fork
- 14.3k
- Merge trung bình
- 2 ngày 4 giờ
- Pull request đã merge (30 ngày)
- 132
Mô tả
### 🔎 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)
Hướng dẫn đóng góp
Hướng nghiên cứu
Bắt đầu với bản tái hiện TypeScript Playground được liên kết và mẫu mã cho thấy một const được thu hẹp bên trong một hàm có phạm vi khối. Theo dõi cách xử lý việc thu hẹp luồng điều khiển đối với các khai báo hàm cục bộ và xác minh rằng ví dụ không còn báo lỗi, đồng thời vẫn giữ nguyên hành vi strict-mode được mô tả trong issue.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Đánh giá
- Công nghệ
- typescript
- Lĩnh vực
- compilers
- Loại issue
- Lỗi
- Độ khó
- 4/5
- Thời gian dự kiến
- 3-5 ngày
- Mức độ hoạt động
- Đình trệ
- Độ rõ ràng
- Khá rõ ràng
- Mức phù hợp với người mới
- 45/100