James Wilkins
James Wilkins

Reputation: 7357

Type ... is not a constructor function type

I wrote some code that works in the playground to create an intersection type to allow using either new to create a type, OR call the constructor instead. This works fine in the playground:

module Test {
    export interface IType<TType> {
        new (...args: any[]): TType;
    }

    export interface ICallableType<TInstance, TType extends IType<TInstance>> {
        (): TInstance;
        new (): TInstance;
    }

    class $MyObject extends Object { // ('Object' is here just as an example)
        static abc = 1;
        x = 1;
        y = 2;
    }

    function registerClass<TInstance, TType extends IType<TInstance>>(_type: TType)
    : ICallableType<TInstance, TType> & TType
    {
        return null;
    }

    export var MyObject = registerClass<$MyObject, typeof $MyObject>($MyObject);

    var o = MyObject();
    o.x = 1;

    export class $TestA extends MyObject {
        a = 3;
    }
    var TestA = registerClass<$TestA, typeof $TestA>($TestA);
    var a = TestA();

    export class $TestB extends TestA {
        b = 4;
    }
    var TestB = registerClass<$TestB, typeof $TestB>($TestB);
    var b = TestB();
}

(see here)

Using VS 2017 with the latest updates this doesn't work at all. $TestA extends MyObject fails with Type ICallableType<TInstance, TType> & TType is not a constructor function. Any ideas why? It seems the playground has a bit older version, so was this a breaking change or something?

Upvotes: 1

Views: 4115

Answers (1)

James Wilkins
James Wilkins

Reputation: 7357

Ok, this works in Typescript v2.2, so it would seem the playground is at least v2.2. Visual Studio 2017 (v15.1 / 26403.7) is stuck at Typescript v2.1.5 at the moment, but v2.2 is available in the preview.

If interested, callable class discussion was here: https://github.com/Microsoft/TypeScript/issues/183#issuecomment-296916884

Update: Keep in mind that ES6 classes have "specialize functions", and you will not be able to simply call a class constructor anymore.

Upvotes: 1

Related Questions