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

Generic function parameters seem to ignore typecheck #1073

Closed
deplinenoise opened this issue Nov 6, 2014 · 4 comments
Closed

Generic function parameters seem to ignore typecheck #1073

deplinenoise opened this issue Nov 6, 2014 · 4 comments
Labels
Fixed A PR has been merged for this issue

Comments

@deplinenoise
Copy link

The type checker seems fine with this use of a generic type in a function parameter:

function callMe<T>(value: T, fn: (value: T) => void) : void {
  fn(value);
}

// No error!
callMe(17, (n: string) => console.log(n) );

If callMe is made non-generic and uses hardcoded types then an error is issued as expected:

function callMeConcrete(value: number, fn: (value: number) => void) : void {
  fn(value);
}

// Error as expected!
// TS2345: Argument of type '(n: string) => void' is not assignable to parameter of type '(value: number) => void'.
callMeConcrete(17, (n: string) => console.log(n) );
@RyanCavanaugh RyanCavanaugh added the Fixed A PR has been merged for this issue label Nov 6, 2014
@RyanCavanaugh
Copy link
Member

This was fixed as part of the union types work, see PR #824

@deplinenoise
Copy link
Author

Confirmed fix on HEAD - sorry about the noise.

@deplinenoise
Copy link
Author

I think I spoke too soon - this still fails to generate an error on HEAD:

function callMe<T>(value: T, fn: (value: T) => void) : void {
  fn(value);
}

callMe([1, "foo"], (n: number[]) => console.log(n) );

@RyanCavanaugh
Copy link
Member

That is example considered by design due to function bivariance.

Basically, when we check assignability of a function, we check its parameter types in "both" directions. The type of [1, "foo"] is Array<number|string> so its element type is number|string, and the type number|string is assignable from number, so the check succeeds.

We have an outstanding feature request #222 for turning off function argument type bivariance, which would make this an error.

@microsoft microsoft locked and limited conversation to collaborators Jun 18, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Fixed A PR has been merged for this issue
Projects
None yet
Development

No branches or pull requests

2 participants