簡體   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