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 not callable when using a generic type parameter and union types #50182

Closed
lo1tuma opened this issue Aug 4, 2022 · 2 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@lo1tuma
Copy link

lo1tuma commented Aug 4, 2022

Bug Report

πŸ”Ž Search Terms

  • This expression is not callable.
  • TS2349
  • generic
  • union type

πŸ•— Version & Regression Information

Problem happens in all recent versions of typescript.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

interface EventEmitter<Mapping> {
    on<EventName extends keyof Mapping>(eventName: EventName): void;
}

interface PayloadA {
    readonly foo: number;
    readonly bar: string;
}

interface PayloadB {
    readonly foo: number;
    readonly baz: boolean;
}

type EmitterA = EventEmitter<PayloadA>;
type EmitterB = EventEmitter<PayloadB>;

interface ModuleA {
    readonly type: 'a';
    readonly on: EmitterA['on'];
}

interface ModuleB {
    readonly type: 'b';
    readonly on: EmitterB['on'];
}

function doStuff(mod: ModuleA | ModuleB): void {
    if (mod.type === 'a') {
      mod.on('foo'); // works
    } else {
      mod.on('foo'); // works
    }
    mod.on('foo'); // doesn’t work
}

πŸ™ Actual behavior

The following error is reported when calling mod.on('foo'); without narrowing its exact type:

This expression is not callable.
  Each member of the union type '(<EventName extends keyof PayloadA>(eventName: EventName) => void) | (<EventName extends keyof PayloadB>(eventName: EventName) => void)' has signatures, but none of those signatures are compatible with each other.

πŸ™‚ Expected behavior

Since mod.on('foo') works in all possible branches when narrowing down the type I would expect it to also work without branching and narrowing.

@jcalz
Copy link
Contributor

jcalz commented Aug 4, 2022

Duplicate of #30581, recommended solution is at #47109

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Aug 4, 2022
@lo1tuma
Copy link
Author

lo1tuma commented Aug 5, 2022

@jcalz thanks for pointing that out. I have troubles understanding the recommended solution and applying it for my use-case. I’ve posted the question on stackoverflow.

@lo1tuma lo1tuma closed this as completed Aug 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants