-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Promises of different types should not be compatible #9953
Comments
In the definition of // in lib.d.ts:
interface Promise<T> {
/*...*/
then<TResult1, TResult2>(onfulfilled: (value: T) => TResult1 | PromiseLike<TResult1>, onrejected: (reason: any) => TResult2 | PromiseLike<TResult2>): Promise<TResult1 | TResult2>;
/*...*/
// then(): Promise<T>; <===== comment this one out
/*...*/
}
// in code.ts:
const x: Promise<string> = Promise.resolve("");
const y: Promise<number> = x; // ERROR: 'Promise<string> is not assignable to 'Promise<number>'
|
I came up with those overloads in #9193, but under closer examination they are actually subtly wrong. TypeScript's model of function arguments assumes that extra args beyond those declared in the signature are ignored - and therefore, a function signature is assignable to a function signature with more parameters. Although you can pass 0 or 1 arguments to I think the right way to declare
EDIT: This only fixes the problem when |
Is this still an issue? const commits: Promise<number> = Promise.resolve('foo') // no error! |
thanks @OliverJAsh. this should be fixed after @rbuckton's latest change to the Promise definitions. |
You can still do this: const x: Promise<number | string> = Promise.resolve("")
const y: Promise<number> = p Here's how that causes errors: function f(f: () => Promise<{ x: number }>) {}
f(async () => !true ? { x: 1 } : "") (not sure why the error happens for Meaning, an async function can return a value of the wrong type if it has multiple returns (and thus returns a union type, which is a subtype of the correct type.) There's a fix: interface Promise<T> { __promiseBrand: T } This enforces the Promise type as if it already had the value, which is probably how people want to view it -- if |
Fixed by #15104. |
TypeScript Version: nightly
Code
Expected behavior:
Compiler error on line 2.
Actual behavior:
No error.
The text was updated successfully, but these errors were encountered: