-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Incorrect overload selected for Array.prototype.map(...)
#47571
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
Comments
Inference doesn't do normal overload resolution per se, instead it performs structural inference between the signatures to try to line things up. Is there a real definition of |
@RyanCavanaugh, this is an approximation. Basically, this is a helper function that gets a string property of an object or returns a string if a string is passed instead of an object. type ObjWithFoo = {foo: string};
declare function getFoo(foo: string | ObjWithFoo): string;
declare function getFoo(url: ObjWithFoo | string | null | undefined): string | null | undefined;
declare const arr: Array<string | ObjWithFoo>;
export const works: string[] = arr.map((v) => getFoo(v));
export const fails: string[] = arr.map(getFoo);
// Err: ^^^ Type '(string | null | undefined)[]' is not assignable to type 'string[]' |
Conditional types will get instantiated, so I'd recommend this: type ObjWithFoo = {foo: string};
declare function getFoo<T extends ObjWithFoo | string | null | undefined>(url: T): T extends undefined | null ? T : string;
declare const arr: Array<string | ObjWithFoo>;
export const works: string[] = arr.map((v) => getFoo(v));
export const alsoWorks: string[] = arr.map(getFoo);
declare const arrU: Array<string | ObjWithFoo | undefined>;
export const chk = arrU.map(getFoo); // Array<string | undefined> |
@RyanCavanaugh thanks! |
Will this bug be fixed? The way using the conditional types looks like a work-around. |
Summary of others' points from duplicate #61398, for the benefit of anyone else landing here from search:
|
Bug Report
π Search Terms
overload, array.prototype.map
π Version & Regression Information
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
It fails to select the correct overloard.
π Expected behavior
It is supposed to select the correct overload.
The text was updated successfully, but these errors were encountered: