[英]How to define an object that is also a function (object from interface) in one statement without type assertion?
由于在JavaScript函数中对象也是对象,因此TypeScript接口可以同时是对象和函数,如下所示:
//TS:
interface ITest {
(arg: any): void
field: number
}
let test: ITest = ((arg: any) => { }) as ITest
test.field = 123
test("foo")
test.field = 456
//JS:
var test = (function (arg) { });
test.field = 123;
test("foo");
test.field = 456;
在那行let test: ITest =
它不会抱怨我不遵守该接口,因为我对ITest
进行了类型声明。 但是,我想在一个语句中定义整个对象。 就像是:
let test: ITest = {
((arg: any) => { }), // Cannot invoke an expression whose type lacks a call signature
field: 123,
}
但是失败了。 这有可能吗?
据我所知,没有类型断言就无法做到这一点。 混合类型的文档也使用这种方式,例如
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getCounter(): Counter {
let counter = <Counter>function (start: number) { };
counter.interval = 123;
counter.reset = function () { };
return counter;
}
let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.