TypeScript中的初学者错误

时间:2017-12-04 09:57:14

标签: 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?

1 个答案:

答案 0 :(得分:1)

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

如果将鼠标悬停在MyClass的{​​{1}}上,您会看到工具提示告诉您它指的是变量而不是类。编译器没有捕到这个的原因是new MyClass()被隐式输入MyClass所以它可以是构造函数。如果您使用了anylet,那么如果您使用了const选项,则会出现错误。