microsoft / microsoft/TypeScript
Explain why private and protected members in a class affect their compatibility
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ả
TypeScript Version: up to 2.5.2 at least
In the doc a short paragraph explains that private and protected members in a class affect their compatibility.
I have been searching for a while in the design goals, on SO etc... but could not find a decent explanation of the rationale. Could we:
- either document the rationale (in the paragraph above?
- or consider evolving the language?
Note: I found one rationale close to what I am looking for, but you could imagine that the language "reserves" the private names but does not compel to use them.
Code
This behavior is especially an issue in unit testing where you want to mock a class, disregarding its internals...
class MyClass {
pubfield = 0;
private privfield1 = 0;
constructor(private privfield2: number) {}
private method(): void {}
}
class MyClassMock implements MyClass {
pubfield: number;
// *** compile errors on missing properties ***
}
Expected behavior:
I would like to only care about the public contract that a class-under-test can possibly use from my mock.
Actual behavior:
I cannot limit my mock to the public fields.
The ugly workaround I found is the following:
class MyClass {
pubfield = 0;
private privfield1? = 0;
private privfield2? = 0;
// do not use the shortcut notation because the constructor param is not optional!
constructor(privfield2: number) {
this.privfield2 = privfield2;
}
private method?(): void {}
}
class MyClassMock implements MyClass {
pubfield: number;
}
What I do not like is that I have to modify the semantics of my class to be able to mock it and that I am scared that a future overzealous refactoring may use the shortcut notation for fields declaration in the constructor... making the constructor param optional (!)
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 phần Private and Protected Members in Classes trong pages/Type Compatibility.md và đọc bình luận issue được liên kết về cơ sở lý luận hiện có. So sánh phần giải thích đó với ví dụ mock và các phương án thay thế được yêu cầu. Được xem là hoàn tất khi cơ sở lý luận đã được ghi lại rõ ràng hoặc câu hỏi về thiết kế ngôn ngữ nhận được một quyết định được ghi lại.
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
- Tài liệu
- Độ 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
- 35/100