将类作为参数传递会导致“不可更新"错误 [英] Passing class as parameter causes "is not newable" error

查看:15
本文介绍了将类作为参数传递会导致“不可更新"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个类作为参数传递给某个函数,该函数将实例化这个类并返回它.这是我的代码:

I'm trying to pass a class as a parameter to some function, that will instantiate this class and return it. Here is my code:

module A.Views {
  export class View { ... }
}

module A.App {
  export class MyApp {
    ...
    registerView(viewKlass:A.Views.View):void
    {
        var test = new viewKlass;
    } 
  }
}

当我试图编译这个时,我得到:

When i'm trying to compile this, i'm getting:

(...): Value of type 'Views.View' is not newable.

我做错了什么?

如果一个 newable 类型值是一个对象构造函数,我如何在运行时传递构造函数?

If a newable type value is an object constructor how do i pass the constructor function at runtime?

推荐答案

我们需要用 typeof(MyClass) 来区分函数签名中的对象和类.

We need something to say typeof(MyClass) to distinguish objects from classes in function signatures.

无论如何,您实际上可以通过使用构造函数类型签名来解决您的问题.考虑这个类:

Anyway, you can actually solve you problem by using constructor type signature. Considering this class:

class MyClass {
    constructor (private name: string) {
    }
}

要将该类作为可以在函数中实例化的类型传递,您实际上必须像这样复制类构造函数签名:

To pass that class as a type that you can then instantiate in a function, you actually have to duplicate the class constructor signature like this:

function sample(MyClass: new (name: string) => MyClass) {
    var obj = new MyClass("hello");
}

在 codeplex 上找到了一个简单的解决方案:

EDIT : There is a simple solution found on codeplex:

你必须像这样为你的类创建一个接口:

You have to create an interface for your class like this:

interface IMyClass {
    new (name: string): MyClass;
}

然后,在您的函数签名中使用它:

Then, use it in your function signature:

function sample(MyClass: IMyClass) {
    var obj = new MyClass("hello");
}

这篇关于将类作为参数传递会导致“不可更新"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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