如何声明返回自己原型的函数的TypeScript类型?

时间:2019-03-19 20:28:03

标签: typescript

我正在尝试编写类型定义,这将导致以下代码进行类型检查:

// MyThing becomes the prototype, but can't be created with `new`
const created = MyThing("hello");

// inferred type of `created` should make `takeAction` be available
created.takeAction();

function sampleFunction(arg: string | MyThing) {
    if (arg instanceof MyThing) {
        // instanceof check should make `takeAction` be available
        arg.takeAction();
    }
}

sampleFunction(created);

到目前为止,我已经尝试过:

interface MyThing {
    takeAction(): void;
}

declare function MyThing(id: string): MyThing;

可行,除了instanceof不能正确缩小类型。我也尝试过:

declare class MyThing {
    constructor(id: string);
    takeAction(): void;
}

但是,这会在声明created的行上导致错误,因为class不能被调用。我还尝试了几种类型合并的变体,以将调用接口添加到已声明的MyThing类中,但这都不起作用:在每种情况下,我都会收到此错误消息:

Value of type 'typeof MyThing' is not callable. Did you mean to include 'new'?

不幸的是,我试图描述一个现有的代码库,因此不要求使用new MyThing

有没有办法正确声明MyThing的类型?

1 个答案:

答案 0 :(得分:1)

从标准库中记下声明,如下所示:

interface Array<T> {
    length: number;
    //...
}
interface ArrayConstructor {
    // ...
    new <T>(arrayLength: number): T[];
    <T>(arrayLength: number): T[];
    readonly prototype: Array<any>;
}

declare const Array: ArrayConstructor;

我们可以将MyThing声明为:

interface MyThing {
    takeAction(): void;
}
interface MyThingConstructor {
    readonly prototype: MyThing;
    (id: string): MyThing;
}
declare const MyThing: MyThingConstructor;