1

I'm a beginner in TypeScript and wrote the following code in MVC5 application:

Controller:

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

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>

TypeScript:

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"
    ]
}

I've got the following error:

TypeError: MyClass is not a constructor.

How can I run my first TypeScript?

tesicg
  • 3,705
  • 13
  • 55
  • 96
  • 1
    Possible duplicate of [Javascript "Not a Constructor" Exception while creating objects](https://stackoverflow.com/questions/10107198/javascript-not-a-constructor-exception-while-creating-objects) – CodeCaster Dec 04 '17 at 10:02

1 Answers1

1

Don't use the same name for the class and the variable, as that will mean in the onload function context MyClass will refer to the variable not the class.

If you hover over the MyClass in new MyClass() you will see the tooltip tell you it is referring to the variable not the class. The reason the compiler did not catch this is that MyClass is implicitly typed to any so it can be a constructor. If you would have used let or const you would have gotten an error, also if you had used the noImplicitAny option.

Titian Cernicova-Dragomir
  • 157,784
  • 15
  • 245
  • 242
  • I use VS2013 and put "let" instead of "var", but there's no compiler error. – tesicg Dec 04 '17 at 10:09
  • That is strange, on version 2.6.2 with no options specified, I get `error TS2448: Block-scoped variable 'MyClass' used before its declaration` – Titian Cernicova-Dragomir Dec 04 '17 at 10:11
  • No. You're right. The error comes up in compile time. I've made mistake by putting "let" in class only, but not in calling code. When I put "let" in calling code as well, the compiler error has been appeared. – tesicg Dec 04 '17 at 10:41