Content-Length: 280057 | pFad | https://github.com/microsoft/TypeScript/issues/9765

43 Function shapes with union typed params incorrectly accept more restrictive functions · Issue #9765 · microsoft/TypeScript · GitHub
Skip to content

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

Closed
@lucasray

Description

@lucasray

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
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixedFixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions









      ApplySandwichStrip

      pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


      --- a PPN by Garber Painting Akron. With Image Size Reduction included!

      Fetched URL: https://github.com/microsoft/TypeScript/issues/9765

      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy