使用typescript中的属性构建一个函数对象 [英] build a function object with properties in typescript

查看:1369
本文介绍了使用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天全站免登陆