我正在尝试编写类型定义,这将导致以下代码进行类型检查:
// 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
的类型?
答案 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;