如何在一个语句中定义一个对象,该对象也是一个函数(来自接口的对象),而无需类型断言



由于在 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;

最新更新