microsoft / microsoft/TypeScript

New operator should return object returned by constructor

Đang mở
#38,519 10 bình luận 11 reaction 0 người được giao Xem trên GitHub

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

new, operator, constructor, return, object

Suggestion

in javascript, calling with the operator new a function that returns an object does not resolves to the created instance but to the object returned by the function

Typescript should do the same.

That could offer a better compliance with the ECMAScript standard.

Use Cases

This can for example allow to create async constructor (see examples)

Examples

function foo(returnDate = false) {
  this.bar = 1;
  if(returnDate) return new Date()
}
const obj1 = new foo() // ES resolves to a foo instance ; typescript get error "ts(2350)"
const obj2 = new foo(true) // ES resolves to a Date     ; typescript get error "ts(2350)"
obj1 instanceof foo // true
obj2 instanceof foo // false

// obj1 and obj2 type should be foo | Date

Use case example: async constructor:

class Foo {
  constructor() {
    return Promise.resolve().then(() => this);
  }
}

const foo1 = await new Foo();
const foo2 = new Foo(); // foo2 is Promise<Foo> ; ts consider foo2 as Foo

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. 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.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu bằng việc xem xét đường dẫn kiểm tra kiểu của TypeScript cho toán tử new và các kiểu trả về của constructor; issue không nêu tệp, bài kiểm thử hay điểm vào nào. Sử dụng các ví dụ JavaScript làm tham chiếu về hành vi, bao gồm cả các constructor trả về một Date hoặc Promise, và đảm bảo các kiểu được suy luận khớp với kết quả khi chạy mà không thay đổi JavaScript được phát ra.

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
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
25/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.