Skip to content
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

Type safety can be lost if an overloaded function is passed as a parameter #14394

Closed
Gekkio opened this issue Mar 1, 2017 · 2 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@Gekkio
Copy link

Gekkio commented Mar 1, 2017

TypeScript Version: 2.2.1 + nightly (2.3.0-dev.20170301)

Code

declare function head(str: string): string;
declare function head<T>(arr: T[]): T;

const numberLists: number[][] = [
  [1, 2],
  [3, 4]
];

// This makes sense
const numberHeads: number[] = numberLists.map(head);

// This shouldn't compile
const stringHeads: string[] = numberLists.map(head);

// This shouldn't compile
const booleanHeads: boolean[] = numberLists.map(head);

// This shouldn't compile
const nullHeads: null[] = numberLists.map(head);

Expected behavior:

Described above in comments

Actual behavior:

All the cases compile, because the return type of all numberLists.map calls here is any[]. Reversing the order of the overloaded function declarations results in this:

  • cases 3, 4 fail to compile (correct)
  • case 1 fails to compile (incorrect)
  • case 2 compiles (incorrect)

There are quite a lot of open issues involving function overloading, but I couldn't find one about forced any-typed return values, which are a silent killer in a codebase because even noImplicitAny doesn't catch these. I wouldn't mind if all the use sites required extra types, but in this case I don't seem to have a way of avoiding accidental loss of type safety.

@Gekkio
Copy link
Author

Gekkio commented Mar 1, 2017

Also, if I call the function using a lambda instead ( numberLists.map(x => head(x)) ), all the cases work as expected.

@mhegazy
Copy link
Contributor

mhegazy commented Mar 2, 2017

Please see #8397 for more details.

@mhegazy mhegazy added the Duplicate An existing issue was already created label Mar 2, 2017
@mhegazy mhegazy closed this as completed Apr 21, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants