1

The function works fine without the type declarations. As soon as I assign the types of variables, I get the errors:

Uncaught SyntaxError: Unexpected token ':', and: Uncaught ReferenceError: convertToCelcius is not defined at HTMLButtonElement.onclick (teamtree.html:15).

All I changed was assigning the variables their types and I'm not sure what these errors are referring to. My guess is some logical error passing the HTML input value (a string, right?) to the TS function as a string parameter.

The HTML looks as so:

   <div class="main">
        <input id="fahVal" name="fahVal" type="text" placeholder="Enter Fahrenheit Value"></input>
        <button class="button" onclick='convertToCelcius(fahVal.value)'>Convert to Celcius</button>
    </div>

And the TypeScript:

function convertToCelcius(fahVal: string) {
    let celVal: number = (+fahVal - 32) * 5/9;
    document.getElementById("display").innerHTML = `<h1> ${celVal.toFixed(0)} </h1>`;
}
Andru
  • 5,954
  • 3
  • 39
  • 56
  • 1
    Are you trying to run the TypeScript code in the browser directly? Because browsers don't understand TypeScript. You need to convert the TypeScript code to JavaScript before passing it to the browser to run. – radiantshaw May 22 '21 at 12:10
  • You were right. My bad it's my first time with TypeScript. Thanks – James Serenity May 22 '21 at 18:26
  • Does this answer your question? [How to compile TypeScript code in the browser?](https://stackoverflow.com/questions/23075748/how-to-compile-typescript-code-in-the-browser) – Lux May 23 '21 at 13:16

1 Answers1

1

TypeScript is a superset of JavaScript. That means that it adds extra syntax (the types) to JavaScript code to make it type-safe. These syntax extensions are not part of JavaScript language which the browser understands. That's why your code is working without the types, but not with them.

TypeScript comes with the TypeScript compiler which converts your TypeScript code into JavaScript code. Thereby it strips off all of the TypeScript syntax and converts the code in a way so that it is type-safe.

That being said, you cannot run TypeScript code directly in your browser by just typing your html file location into the browser's address bar.

You have to first install typescript (e.g. via npm install typescript in your project directory where your TypeScript file lies) and then run npx tsc to compile your TypeScript code to JavaScript. The resulting file will run in the browser.

See the TypeScript installation page for more details about how to use TypeScript.

Andru
  • 5,954
  • 3
  • 39
  • 56