TypeScript中的初学者错误

特西格

我是TypeScript的初学者,并在MVC5应用程序中编写了以下代码:

控制器:

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
}

视图:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/app.js"></script>
</head>
<body>
    <div id="cont"></div>
</div>
</body>
</html>

打字稿:

class MyClass {
    public render(divId: string, text: string) {
        var el: HTMLElement = document.getElementById(divId);
        el.innerText = text;
    }
}

window.onload = () => {
    var MyClass = new MyClass();
    MyClass.render("cont", "Hello World");
};

tsconfig.json:

{
    "compilerOptions": {
        "noImplicitAny": false,
        "noEmitOnError": true,
        "removeComments": false,
        "sourceMap": true,
        "target": "es6",    
        "outDir": "../Scripts"
    },
    "exclude": [
        "node_modules",
        "wwwroot"
    ]
}

我遇到以下错误:

TypeError:MyClass不是构造函数。

如何运行我的第一个TypeScript?

提香·切尔尼科娃·德拉戈米尔

不要为类和变量使用相同的名称,因为这将意味着在onload函数上下文MyClass中将引用变量而不是类。

如果将鼠标悬停在上MyClassnew MyClass()您将看到工具提示,告诉您它是指变量而不是类。编译器未捕获此错误的原因MyClass是隐式键入为,any因此它可以是构造函数。如果您曾经使用过,let或者const遇到了错误,那么您也可以使用该noImplicitAny选件。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章