You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Function shapes with union typed params incorrectly accept more restrictive functions #9765
Functions typed to accept union typed params incorrectly typecheck against functions whose params only match a subset of the union. Example:
interfaceCallback{(value: string|number): void;}// expect this to workconstmany: Callback=(value: string|number|boolean)=>{// ...}// expect a type error hereconstone: Callback=(value: string)=>{// ...}many(1);// should work, does workone(1);// shouldn't work, does work *many("hello");// should work, does workone("hello");// should work, does workmany(true);// shouldn't work, doesn't workone(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.
interfaceSomeLib{onChange: (callback: (newValue: string|null)=>void)=>void;}constfoo: SomeLib= ...;foo.onChange((newValue: string)=>{// oops, I forgot newValue may not be defined, but this compiles});
Activity
RyanCavanaugh commentedon Jul 15, 2016
See https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-function-parameters-bivariant
lucasray commentedon Jul 16, 2016
Interesting, makes sense, thanks for the link. I'll keep an eye out for covariant/contravariant annotations.