由于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,
}
但是失败了。这有可能吗?
答案 0 :(得分:0)
据我所知,没有类型断言就无法做到这一点。 Hybrid Types的文档也以这种方式使用它,例如
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;