[英]Function variable assigned to a Class using Typescript
Say you have a Typescript class
like this: 假设您有一个这样的Typescript
class
:
class CompExt extends Comp {
public static sum(a: number, b: number): number {return a+b};
};
The function sum will be sligtly different from the original class and it must be static. 函数sum将与原始类明显不同,并且必须是静态的。
Your actual code is 您的实际代码是
let ff: Function = CompExt;
console.log('the summ works fine',ff.sum(1,2));
Both the code editor and compilation will warn me this: 代码编辑器和编译都会向我发出警告:
bas.ts(47,16): error TS2339: Property 'sum' does not exist on type 'Function'.
Is there a way to avoid compilation errors? 有没有办法避免编译错误? If I use
any
rather than Function
everthing is fine but I was wondering if Typescript supports such style. 如果我使用
any
而不是Function
一切都很好,但是我想知道Typescript是否支持这种样式。
Just don't specify the type to be a Function
because it's not a generic function, it's CompExt
. 只是不要将类型指定为
Function
因为它不是泛型函数,而是CompExt
。
If you really want to specify the type, you can use: let ff: typeof CompExt = CompExt
. 如果确实要指定类型,则可以使用:
let ff: typeof CompExt = CompExt
。
A possible solution to your situation can be provided using decorators. 可以使用装饰器来解决您的情况。 Check this answer Static property on a class
检查此答案类的静态属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.