我是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
中将引用变量而不是类。
如果将鼠标悬停在上MyClass
,new MyClass()
您将看到工具提示,告诉您它是指变量而不是类。编译器未捕获此错误的原因MyClass
是隐式键入为,any
因此它可以是构造函数。如果您曾经使用过,let
或者const
遇到了错误,那么您也可以使用该noImplicitAny
选件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句