使用 TypeScript 中的属性构建函数对象 [英] Build a function object with properties in TypeScript

查看:21
本文介绍了使用 TypeScript 中的属性构建函数对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数对象,它也有一些属性.例如在 JavaScript 中我会这样做:

I want to create a function object, which also has some properties held on it. For example in JavaScript I would do:

var f = function() { }
f.someValue = 3;

现在在 TypeScript 中,我可以将它的类型描述为:

Now in TypeScript I can describe the type of this as:

var f: { (): any; someValue: number; };

但是我实际上无法构建它,而不需要演员.如:

However I can't actually build it, without requiring a cast. Such as:

var f: { (): any; someValue: number; } =
    <{ (): any; someValue: number; }>(
        function() { }
    );
f.someValue = 3;

如果没有演员,你会如何构建这个?

How would you build this without a cast?

推荐答案

因此,如果需要简单地构建该函数并将该函数分配给f"而不进行强制转换,那么这里有一个可能的解决方案:

So if the requirement is to simply build and assign that function to "f" without a cast, here is a possible solution:

var f: { (): any; someValue: number; };

f = (() => {
    var _f : any = function () { };
    _f.someValue = 3;
    return _f;
})();

本质上,它使用自执行函数字面量来构造"一个​​对象,该对象将在分配完成之前匹配该签名.唯一奇怪的是,函数的内部声明必须是any"类型,否则编译器会抱怨您要分配给对象上尚不存在的属性.

Essentially, it uses a self executing function literal to "construct" an object that will match that signature before the assignment is done. The only weirdness is that the inner declaration of the function needs to be of type 'any', otherwise the compiler cries that you're assigning to a property which does not exist on the object yet.

稍微简化代码.

这篇关于使用 TypeScript 中的属性构建函数对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆