-
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
Incorrect inferred return type when returning object literal from lambda bound to generic parameter #5487
Comments
I guess that function return type inference (maybe kicked off by contextual typing of the object literal?) interferes with fixing the type parameters. |
Unfortunately, this is a real circularity in the contextual typing algorithm:
The funny part is that after the circularity is detected, the compiler can get the type of the object literal in I'm not sure if the circularity detection that throws away the result is correct. I'll look at that next. |
@ahejlsberg, in |
I came across what I believe this issue is today, where literals could be contextually inferred, but don't seem to be... Even more surprising, is where they appear to be inferred contextually they suddenly widen without implicit types. The real world use case was using function truePromise(): Promise<true> {
return Promise.resolve(true); // Type 'boolean' is not assignable to type 'true'.
}
interface Wrap<T> {
value: T;
}
function wrap<T>(value: T): Wrap<T> {
return { value };
}
function wrappedFoo(): Wrap<'foo'> {
return wrap('foo'); // Type 'string' is not assignable to type '"foo"'.
}
function wrapBar(value: 'bar'): Wrap<'bar'> {
return { value };
}
function wrappedBar(): Wrap<'bar'> {
const value = 'bar'; // const value: "bar"
const inferred = wrapBar(value); // const inferred: Wrap<"bar">
const literal = wrapBar('bar'); // no error!
const value2: string = 'bar';
const literal2 = wrapBar(value2); // Argument of type 'string' is not assignable to parameter of type '"bar"'.
return wrap(value); // Type 'string' is not assignable to type '"bar"'. ?!?!?!
}
function wrappedBaz(): Wrap<'baz'> {
const value: 'baz' = 'baz';
return wrap(value);
} The surprising one was |
@kitsonk This issue might interest you: #10195 Here's the workaround for your example: (playground) The error for |
Closing as the bug no longer reproduces. We now infer the correct type. |
When passing a function as a generic type T, the compiler correctly infers the return type when passing a previously declared function, but not when the same function is passed as an inline lambda. This seems to only happens with object literals. Classes and builtin return types are inferred properly.
The text was updated successfully, but these errors were encountered: