繁体   English   中英

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

[英]How to declare TypeScript type of function that returns own prototype?

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

// 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声明created的行上导致错误,因为无法使class可调用。 我还尝试了一些类型合并的变体,以将调用接口添加到已声明的MyThing类,但这也不起作用:在每种情况下,我都收到以下错误消息:

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

不幸的是,我试图描述一个现有的代码库,所以要求new MyThing不是一种选择。

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

从标准库中记下声明 Array 的注释,如下所示:

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM