microsoft / microsoft/TypeScript

Allow async functions to return union type T | Promise<T>

Đang mở
#33,595 17 bình luận 28 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

"the return type of an async function or method must be the global Promise type"
"typescript promise union type"

Suggestion

You can explicitly declare a function's return type as a union that includes a Promise<T>.
While this works when manually managing promises, it results in a compiler error when using the async/await syntax.

For example, a function can have a return type T | Promise<T>. As the developer of an abstraction layer, this allows you to have an abstract return type that can be handled in a typesafe way but doesn't dictate implementation to consumers.

This improves developer ergonomics for consumers of a library without reducing the safety of the type system by allowing developers to change implementation as the system evolves while still meeting the requirements of the abstraction layer.

This only works, currently, if the developer explicitly manages the promises. A developer may start with something like this:

type ActionResponse<T> = T | Promise<T>;

function getCurrentUsername(): ActionResponse<string> {
  return 'Constant Username';
}

async function logResponse<T>(response: ActionResponse<T>): Promise<void> {
  const responseValue = await response;
  console.log(responseValue);
}

logResponse(getCurrentUsername());
// Constant Username

Then, if the consumer of logResponse switches to a promise based method, there's no need to change the explicit return type:

function getCurrentUsername(): ActionResponse<string> {
  // return 'Constant Username';
  return Promise.resolve('Username from Database');
}

// Username from Database

However, if the consumer of logResponse prefers to use async/await instead of manually managing promises, this no longer works, yielding a compiler error instead:

The return type of an async function or method must be the global Promise type.

One workaround is to always return promises even when dealing non-async code:

async function getCurrentUsername(): Promise<string> {
  return 'Constant Username';
  // return Promise.resolve('Username from Database');
}

Another workaround is to use an implicit return type:

async function getCurrentUsername() {
  return Promise.resolve('Username from Database');
}

These do get around the issue for sure, but they impose restrictions on consumers of the abstraction layer causing it to leak into implementation.

It seems valuable for the behavior to be consistent between using async/await and using Promise directly.

Use Cases

This feature would be useful for developers who are building abstraction layers and would like to provide an abstract return type that could include promises. Some likely examples are middlewares, IoC containers, ORMs, etc.

In my particular case, it's with inversify-express-utils where the action invoked can be either async or not and the resulting behavior doesn't change.

Examples

// this type
type ActionResponse<T> = T | Promise<T>;

// supports this function
function getCurrentUsername(): ActionResponse<string> {
  return 'Constant Username';
}

// as it evolves over time into this function
async function getCurrentUsername(): ActionResponse<string> {
  return Promise.resolve('Username from Database');
}

// and is handled transparently by functions like this
async function logResponse<T>(response: ActionResponse<T>): Promise<void> {
  const responseValue = await response;
  console.log(responseValue);
}

logResponse(getCurrentUsername());

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

Issue không nêu tệp trình biên dịch TypeScript hay bài kiểm thử nào. Trước tiên, hãy tái hiện lỗi kiểu trả về async đã được báo cáo bằng các ví dụ được cung cấp, sau đó xác định chẩn đoán của trình biên dịch và phạm vi kiểm thử của nó; công việc được xem là hoàn tất khi một hàm async có thể trả về rõ ràng T | Promise mà vẫn duy trì tính an toàn kiểu.

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

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.