Reputation: 11
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>`;
}
Upvotes: 1
Views: 3091
Reputation: 6204
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.
Upvotes: 1