【问题标题】:The beginners' error in TypeScriptTypeScript 初学者的错误
【发布时间】:2018-05-17 18:14:21
【问题描述】:

我是 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?

【问题讨论】:

标签: typescript


【解决方案1】:

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

如果您将鼠标悬停在new MyClass() 中的MyClass 上,您将看到工具提示告诉您它指的是变量而不是类。编译器没有捕捉到这一点的原因是 MyClass 被隐式键入到 any 所以它可以是一个构造函数。如果你使用了letconst,你会得到一个错误,如果你使用了noImplicitAny 选项。

【讨论】:

  • 我用VS2013,用“let”代替“var”,但没有编译错误。
  • 这很奇怪,在没有指定选项的 2.6.2 版本上,我得到 error TS2448: Block-scoped variable 'MyClass' used before its declaration
  • 没有。你说得对。错误出现在编译时。我只在课堂上放“let”而不是在调用代码中犯了错误。当我在调用代码中也加上“let”时,出现了编译器错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
  • 2011-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多