microsoft / microsoft/TypeScript
Type inference only works on the same line as the variable declaration
Chưa có ai nhận issue này.
- Ngôn ngữ chính
- Go
- Star
- 111k
- Fork
- 14.4k
- Merge trung bình
- 1 ngày 19 giờ
- Pull request đã merge (30 ngày)
- 117
Mô tả
I ran into this odd behavior while writing some tests, that do the typical describe, declare a closure-scope variable, and in beforeEach, assign some object to that variable that is used in each of the tests inside.
Search Terms:
infer, inference, closure, scope, broken, any, cast
Initially, I thought it was limited to closure scope, but I then started reducing the reproduction sample more and more, and realized, it's broken even if it's on the very next line:
Code
// given
interface Foo {
id: string;
}
function make(): Foo {
return {
id: 'akatechis',
}
}
// u1 is correctly inferred to be of type Foo.
let u1 = make();
// u2 is incorrectly inferred to be of type any.
let u2;
u2 = make();
// this was the scenario in which I originally ran into this:
// a closure scoped variable that is assigned in an inner function
function outer () {
// u3 is inferred to be of type any
let u3;
return {
inner() {
// u3 here is still any
u3 = make();
// surprisingly, returning u3 here causes the return type of inner() to be Foo, not any???
return u3;
}
}
}
Expected type declarations:
interface Foo {
id: string;
}
declare function make(): Foo;
declare let u1: Foo;
declare let u2: Foo; // <---- this should have been inferred to be Foo
declare function outer(): {
inner(): Foo;
};
Actual type declarations:
interface Foo {
id: string;
}
declare function make(): Foo;
declare let u1: Foo;
declare let u2: any;
declare function outer(): {
inner(): Foo;
};
Playground Link: playground
Related Issues:
The only thing that I found somewhat close to this issue was the question in the FAQ about unused generic types causing type widening, but I don't think this is it, because I'm not using generics here.
Hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
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à so sánh các khai báo được suy luận cho u1, u2 và outer(). Đọc mục FAQ liên quan về type widening để loại trừ cách giải thích đó, sau đó xác định hành vi suy luận kiểu chịu trách nhiệm cho sự không khớp. Hoàn thành khi u2 được suy luận là Foo trong khi vẫn giữ nguyên kết quả outer() được hiển thị.
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
- Đặc tả rõ ràng
- Mức phù hợp với người mới
- 35/100