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

Function shapes with union typed params incorrectly accept more restrictive functions #9765

Closed
lucasray opened this issue Jul 15, 2016 · 2 comments
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed Fixed A PR has been merged for this issue

Comments

@lucasray
Copy link

TypeScript Version: 2.0.0 beta

Functions typed to accept union typed params incorrectly typecheck against functions whose params only match a subset of the union. Example:

interface Callback {
  (value: string | number): void;
}

// expect this to work
const many: Callback = (value: string | number | boolean) => {
  // ...
}

// expect a type error here
const one: Callback = (value: string) => {
  // ...
}

many(1);       // should work, does work
one(1);        // shouldn't work, does work *
many("hello"); // should work, does work
one("hello");  // should work, does work
many(true);    // shouldn't work, doesn't work
one(true);     // shouldn't work, doesn't work

Expected
one throws a type error, since string | number is not assignable to string.

Actual
one compiles fine.

This comes up in real code when declaring a callback whose params may not be defined, e.g.

interface SomeLib {
  onChange: (callback: (newValue: string | null) => void) => void;
}

const foo: SomeLib = ...;
foo.onChange((newValue: string) => {
  // oops, I forgot newValue may not be defined, but this compiles
});
@RyanCavanaugh
Copy link
Member

@RyanCavanaugh RyanCavanaugh added the Design Limitation Constraints of the existing architecture prevent this from being fixed label Jul 15, 2016
@lucasray
Copy link
Author

Interesting, makes sense, thanks for the link. I'll keep an eye out for covariant/contravariant annotations.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed Fixed A PR has been merged for this issue
Projects
None yet
Development

No branches or pull requests

3 participants