-
Notifications
You must be signed in to change notification settings - Fork 12.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Allow async functions to return union type T | Promise<T> #33595
Comments
I don't understand the need for this. Why does the second You only need the |
Hey @RyanCavanaugh, thanks for responding. It's hard to reproduce my use case with a trivial example. Specifically, I'm using
Eventually, we need to get the user data from the database:
I can make that change without changing the return type if they both return So, up until this point, everything works swimmingly if you start your actions with this definition:
Then, when you realize you need to do something with a promise before returning, you could change the method like so:
But, if you prefer the async/await syntax, you can't change your method to this:
One neat thing about The way I've worked around it is to make all controller actions async always. Then I don't have to change anything as the action evolves. But, it seems like it'd be cool if the behavior was consistent between manually chaining promises and using the async/await syntactic sugar (is it fair to call it syntactic sugar? . . . I'm not sure). It seems like it would also be consistent with a function:
Does that make sense? Thanks again! |
Thanks, that's a nice explanation! |
Some previous discussion/examples about this: #6686 (comment) and onward |
|
@falsandtru, thanks very much for your thoughts! I find them very valuable. TL;DRI think after writing way too many words here, I've refined my opinion down to this: Or, maybe even less verbose: Original Response :)
I agree that "All non-trivial abstractions, to some degree, are leaky." I could easily change it to The downside is that now an implementation detail of an abstraction layer is leaking into my codebase dictating a coding convention that's unnecessary and difficult to discover. What I mean is, one reason not to change Which is why I'd imagine what you mean is something more like, "I personally can't think of a good reason not to change your implementation right now." . I do think that trying to plug leaks in abstraction layers is a pretty good reason, but you're right that it may not be worth it. I haven't looked at the implementation of the async keyword, but it seems like the intent is to provide a more ergonomic syntax for dealing with promises. This is from the ECMA-262 specification:
Right now, in typescript, I have to chose one of the following options:
Just like this function's return type is valid (albeit an oversimplified example that doesn't express the value in returning union types):
I think it would be consistent (and therefore valuable) for this function's return type to also be valid:
I'm not sure that I'd say union types are ambiguous, even as return types. I do think that when abused, union types can be harder to reason about. But, I do feel like union types are pretty explicit. Another personal opinion is leaking in here, but I do like union types as a language feature of TypeScript. I think the type disjunction with union types is valuable, and I also like using type guards for type refinement. Here's a good example of returning a union type (from the TypeScript documentation on union types):
Just to be clear, I don't think you should be allowed to say:
I agree, that's probably wrong. Even though the compiler could infer the return type is implicitly wrapped in a promise, I don't care for it. I feel like if you want implicit typing, use implicit typing . . . but I don't think you should mix the explicitness of the return type with the implicitness of wrapping that type with a promise when the But, that's an entirely different conversation altogether. Considering this function:
This just allows consumers not to care if it's a promise or not. That allows an abstraction layer to say, "hey, if you pass a callback to me, make sure that it returns a This puts the onus of understanding on the abstraction layer and reduces the cognitive overhead of consumers of the abstraction. This kind of thing is useful in DI frameworks, ORMs, test frameworks, etc.
I certainly can only speak for myself; I don't know what everyone wants to read. For me, I don't really associate the In fact, this function may very well return a promise without the async keyword being present. |
Or more briefly, TypeScript has a structural type system and pretty consistently applies it, except with async function return types, where it does a nominal, not structural, check. Usually when you specify parameter and return type annotations on a function in TypeScript, the caller can pass in anything that is assignment-compatible with the parameter types, and the function can return anything that is assignment compatible with the return type. Likewise with variable assignments, property assignments, etc etc. Async function return types are a rare exception to this rule. Even generator functions, which just like async functions always return a known system type, can be annotated with assignment-compatible return types which are checked structurally. IMO there is an inconsistency here. The consequences are arguably not huge, but have been reported in a number of issues over the years so do affect at least some users. I can't really see the downsides of removing this inconsistency. |
I think this hits the nail on the head. This nominal behaviour also prevents libraries from providing richer |
I seem to have found a workaround that seems to work. I pass this type to express. Haven't done deep diagnostics on it but it made all my TS compilation errors + eslint no-misused-promises errors go away, so thought I'd share. type SyncRouteHandler = (req: Request, res: Response) => void;
type AsyncRouteHandler = (req: Request, res: Response) => Promise<void>;
export type RouteHandler = SyncRouteHandler | AsyncRouteHandler; |
To me, this doesn't make sense. The async function doStuff(): string { … are simply incorrect, because it's actually You can, however, define a non- function doStuff(): string | Promise<string> { … for example, depending on some external state: function getUsername(): string | Promise<string> {
if (cache.user != null)
return cache.user.name;
return db.getUser().then((user) => (cache.user = user).name);
} … but making it |
@parzhitsky, thanks for your feedback. I wholeheartedly agree with you that an This particular issue isn't about what an async function getValue() : string | Promise<string> { ... } But, I don't think it would be strange to declare a function like this: async function getValue(): ApiResponse<string> or async function getValue(): StateInitializer<string> And, I don't think it's unreasonable for the author of a library to say, "I can handle either a promise or a non-promise . . . so give me either of those and I'll do the right thing with it," and export a type like: export type ApiResponse<T> = T | Promise<T>;
// or
export type StateInitializer<T> = T | Promise<T>; I think that the question really boils down to this: Is it reasonable for a function to accept a function doWork<T>(value: T | Promise<T>) { ... }
function saveSomething<T>(value: T | Promise<T>) { ... }
function logSomething<T>(value: T | Promise<T>) { ... } If it is reasonable for a function to accept a export type Action<T> = T | Promise<T>;
export type DataProvider<T> = T | Promise<T>;
export type Loggable<T> = T | Promise<T>; If those are both reasonable, is it also reasonable for a consumer of this function to declare functions that explicitly return this abstracted type? function handleSomeBehavior(): Action<string> { ... }
function getSomeData(): DataProvider<string> { ... }
function getSomeData(): Loggable<string> { ... } Finally, if it's reasonable to explicitly return an abstracted type, is it reasonable to want to use the async keyword? I don't know these answers. I do know that it's a use case I encountered. I just wanted to be able to say, "this function returns a thing I can pass to this other function" and TypeScript wouldn't let me. :) Does that make any sense at all? It's really hard to explain this with trivial examples. It's too easy to say, "well, just change your trivial example." I was using a pretty popular library at the time that had a function that could take a |
Okay, so, if I understand correctly, you are saying that this is wrong (or weird at least): async function doStuff(): string { … and so is this: async function doStuff(): string | Promise<string> { But there are situations when you can’t really control the structure of the type union, since you don’t create it, like here: import type ApiResponse from "some-library/types";
import { onlyAcceptsApiResponse } from "some-library";
declare function doStuff(): ApiResponse<string>;
onlyAcceptsApiResponse(doStuff()); … and if But you also cannot do this: type UnwrapPromise<Value> =
Value extends PromiseLike<infer Bare> ? UnwrapPromise<Bare> : Value;
type PromiseOnly<Value> =
Promise<UnwrapPromise<Value>>;
async function doStuff(): PromiseOnly<ApiResponse<string>> { … because, while it works, it also requires for you to a) know the implementation of Is this correct? If it is, then I agree with the proposal. Not only that, I would actually go a bit further, and propose to remove the distinction between “bare” and promise-wrapped values in return signatures of async function doStuff(): string { async function doStuff(): Promise<string> { … should be considered indistinguishably identical. |
Yes, this is correct!! I think that this response by @yortus really succinctly describes it: #33595 (comment) Thanks @parzhitsky for joining the discussion! |
I hit a somewhat related issue (that I can't find a more relevant issue for) with types that extend Promise. Specifically, with Prisma2 declare const prisma: unique symbol
type PrismaPromise<A> = Promise<A> & {[prisma]: true} Prisma's API exposes methods like If you write some async function which eventually returns a // This function actually returns a "PrismaPromise" at runtime,
// but there's no way to tell TypeScript that!
async function updateItem(itemId: string, data: unknown) {
await validateChanges(itemId, data);
return prisma2.item.update(itemId, data);
}
// Typescript will error here, despite this being valid at runtime.
prisma2.$transaction(updateItem('foo', {}), updateItem('bar', {})); It would be nice to be able to have typescript infer the Promise type returned, or at least allow us to decorate the method with |
In my case I wanted to declare an optional function that may be async or not and had no trouble doing so: abstract class Reporter {
afterAll?(): void | Promise<void>;
}
class ChartReporter extends Reporter {
async afterAll() {
await saveToFile();
}
}
class CLIReporter extends Reporter {
afterAll() {
console.log("done");
}
}
// Main program:
for (const reporter of reporters) {
await reporter.afterAll?.();
} (full source), hope this helps someone. |
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:
Then, if the consumer of
logResponse
switches to a promise based method, there's no need to change the explicit return type: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:One workaround is to always return promises even when dealing non-async code:
Another workaround is to use an implicit return type:
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
Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: