microsoft / microsoft/TypeScript
Using the "in" operator should make bracket access safe on an object
Đang mở
Chưa có ai nhận issue này.
Awaiting More Feedback
Suggestion
- 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
object in keyof bracket operator in
Suggestion
Checking a key with the "in" operator on an object should make it safe to to use in brackets
Use Cases
Useful when writing functions that process input JSON/doesn't have a concrete type.
Examples
// Ideally this uses TypeScripts control flow logic to allow the bracket access.
function getPropFailsToCompile(data: object, key: string): any {
if (!(key in data)) {
throw new Error("Data is malformed")
}
return data[key]
}
// Compiles but keyof object has type 'never' in Typescript
function getPropCompilesButNotReasonable(data: object, key: keyof object): any {
if (!(key in data)) {
throw new Error("Data is malformed")
}
return data[key]
}
// Best way I've gotten this to work.
function getPropWorks(data: object, key: string): any {
if (!(key in data)) {
throw new Error("Data is malformed")
}
return (<any>data)[key]
}
Checklist
My suggestion meets these guidelines:
- [x ] This wouldn't be a breaking change in existing TypeScript/JavaScript code
- [x ] This wouldn't change the runtime behavior of existing JavaScript code
- [x ] This could be implemented without emitting different JS based on the types of the expressions
- [x ] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- [ x] This feature would agree with the rest of TypeScript's Design Goals.
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 ba ví dụ TypeScript của issue và phần thảo luận xung quanh để hiểu hành vi narrowing được đề xuất cho toán tử "in" và truy cập bằng dấu ngoặc vuông. Hoàn thành khi ví dụ đầu tiên kiểm tra kiểu mà không cần cast, đồng thời giữ nguyên hành vi runtime hiện có của JavaScript.
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ính năng
- Độ 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