Skip to content

No signature when using union type of functions #12835

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

Closed
OliverJAsh opened this issue Dec 11, 2016 · 1 comment
Closed

No signature when using union type of functions #12835

OliverJAsh opened this issue Dec 11, 2016 · 1 comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@OliverJAsh
Copy link
Contributor

v2.1.4

{
    type Fn1 = (x: number) => number;
    type Fn2 = (x: any) => string;

    const fn = 1 as any as Fn1 | Fn2

    fn(1) // error: Cannot invoke an expression whose type lacks a call signature.
}

However, if I change Fn2 to type Fn2 = (x: number) => string; (thus removing the any), the error disappears.

I would like to understand why TypeScript can't handle the former case.

For context, I am trying to build an Option type, where Option = Some | None:

{
    class Some<T> {
        constructor (public t: T) {}
        map<T2>(f: (t: T) => T2): Some<T2> { return new Some(f(this.t)) }
    }

    class None {
        constructor () {}
        map(f: (t: any) => any): None { return new None() }
        get() { throw new Error('foo') };
    }

    type Option<T> = Some<T> | None;

    const option = new Some(1) as Option<number>;

    option.map(x => 1) // error: Cannot invoke an expression whose type lacks a call signature.
}
@mhegazy
Copy link
Contributor

mhegazy commented Dec 12, 2016

A union type has only gets signatures that are identical in all constituents. the reason is there is no meaningful way the compiler can combine these signatures, for the general case, and still grantee type safety. see #10620 for more details.

@mhegazy mhegazy added the Working as Intended The behavior described is the intended behavior; this is not a bug label Dec 12, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

3 participants