【问题标题】:How to define an object that is also a function (object from interface) in one statement without type assertion?如何在没有类型断言的语句中定义一个也是函数的对象(来自接口的对象)?
【发布时间】:2019-06-10 17:59:35
【问题描述】:

由于在 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,
}

但它失败了。这甚至可能吗?

【问题讨论】:

    标签: typescript interface type-assertion


    【解决方案1】:

    据我所知,没有类型断言就无法做到这一点。 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;
    

    【讨论】:

    • @modiX 似乎类型断言是正确的方法,因为官方文档也这样使用它。
    猜你喜欢
    • 1970-01-01
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2021-12-08
    相关资源
    最近更新 更多