TypeScript: Union types not working with old-style overloads

I was just working with Big.js and tried to pass a union type into its constructor function. It seems that union types don’t play nice with old-style overloaded constructors. Please consider the code below that errors with TypeScript 1.4. I would have expected this to work.


interface BigJS_Constructors {
    new (value: number): BigJS;
    new (value: string): BigJS;
    new (value: BigJS): BigJS;
}

interface BigJS extends BigJS_Constructors {
    abs(): BigJS;
    /* more... */
}

var Big : BigJS;

class MyThing {
    public value : BigJS;
    constructor(value: number | string | BigJS) {
        this.value = new Big(value); //This is an error in 1.4.
    }
}

If I change the new signature under BigJS_Constructors to new (value: number | string | BigJS) : BigJS;, and eliminate the other two options, it works fine, but to me the two styles should be identical in this case.

My apologies if I’m doing something stupid here. Thanks!

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 1
  • Comments: 20 (10 by maintainers)

Most upvoted comments

This is an old issue. So it’s very strange that I just ran into this issue recently(this week). The same code work without any problem before(with tsc and tslint, in the past 12 months).

I just ran into this problem trying to write a wrapper function. I second @RyanCavanaugh’s suggestion in https://github.com/Microsoft/TypeScript/issues/1805#issuecomment-84063972.

My cut-down example is:

function foo(x: number);
function foo(x: string);
function foo(x: number|string) {/***/}

var c: number|string;
foo(c); // ERROR: Argument type 'number|string' not assignable to parameter type 'string'

I understand why it doesn’t work, but I was initially surprised by the error given this code is ‘logically’ straightforward and valid.

I notice there are many incoming links to this issue but it hasn’t been updated in a long time. Any updates from the team on this one?