Skip to content

No signature when using union type of functions #12835

Closed
@OliverJAsh

Description

@OliverJAsh

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.
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions