microsoft / microsoft/TypeScript
Static variable may be undefined when constructing an object of the same class
Chưa có ai nhận issue này.
- 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ả
Bug Report
I'm not sure whether this may be a issue that can be fixed or just keep it as is "by design". I haven't found any other issues similar to this one here, at least with the search terms I tried (sorry if someone else already reported this 🙂).
🔎 Search Terms
static, undefined, uninitialized, constructor
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about static variables, variable order initialization, etc., but none of them seem to match this.
At the moment of writing this, TypeScript version is 4.2.3.
⏯ Playground Link
💻 Code
class A {
public static readonly instance: A = new A();
public static readonly constant: number = 1;
public constructor() {
console.log(A.constant, A.constant * 5);
console.log(A.constant.toString());
}
}
🙁 Actual behavior
When calling the constructor to initialize the static variable instance, A.constant is not yet initialized (it's undefined), so the constructor logs undefined, NaN.
In addition, A.constant.toString() gives a javascript execution error, which even in strict mode the compiler doesn't catch.
🙂 Expected behavior
The compiler could tell that constant has type number | undefined at that moment (manually changing the type of constantto number | undefined correctly yields a compiler error) or even rearrange the generated javascript to initialize first constant and then instance (which I think it may be more difficult in more complex scenarios).
Thank you very much!
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 được liên kết trong TypeScript Playground và so sánh JavaScript được phát ra với thứ tự khởi tạo được báo cáo. Theo dõi cách trình kiểm tra kiểu xử lý việc khởi tạo các thuộc tính tĩnh trong quá trình xây dựng, sau đó xác định liệu việc hoàn tất nên là một chẩn đoán, một thay đổi trong quá trình phát ra hay một quyết định thiết kế rõ ràng; xác minh kết quả bằng một trường hợp hồi quy.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Đánh giá
- Công nghệ
- javascript, typescript
- Lĩnh vực
- compilers
- Loại issue
- Lỗi
- Độ khó
- 5/5
- Thời gian dự kiến
- Hơn một tuần
- 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
- 35/100