Display Typescript variable in HTML DOM

To get a typescript variable to display in the DOM, first we need the index.html which will include the app.js file with the script tag.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title<>/title>
  <script src="./app.js">
  </script>
</head>
<body>
</body>
</html>

app.ts uses window.onload = function {…} which loads after the DOM has been created,

window.onload = function() {

let user: string = "Jane";
let sentence: string = `${user} is super
and totally cool!`;

document.body.innerHTML = "<p><strong>" + sentence + "</strong></p>";
}

Unfortunately the last three words “and totally cool!” are not appearing on a new line as would be expected with the `…` notation.

Of course we compile the app.ts file to app.js using,

$ tsc

or to keep watching the file use,

$ tsc -w

See previous post for setup.

Leave a Reply