繁体   English   中英

如何在一个没有类型声明的语句中定义一个对象,该对象也是一个函数(接口中的对象)?

[英]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.

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