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.

TypeScript Notes

See tsconfig.json configuration and compiler options

Install TypeScript if it is not done already,

$ npm install -g typescript

Create a new directory

$ mkdir typescript

Change directory into new typescript directory,

$ cd typescript
$ npm init

Hit enter to apply default to all options. This will create a package.json file in the directory.

$ tsc --init

Creates the tsconfig.json file for configuring typescript compile settings.

$ npm install

Creates the node_modules directory.

In tsconfig.json setting,

"sourceMap": true,

will allow you see a .ts file in the developer tools of the browser and even to debug the .ts file itself and see the immediate result in the browser without needing to compile again.

Install lite-server locally in this directory,

$ npm install lite-server

To install lite-server and add the package to package.json with the –save option flag,

$ npm install lite-server --save

The script,

  "start": "lite-server"

should be added to package.json to run lite-server with

$ npm start

In tsconfig.json

"noImplicitAny: false"

is by default set to false and so any variable with no type declared will be of type ‘any’. However by changing this to ‘true’ then all variables must be declared and will not default to ‘any’.

Create index.html and add the app.js script,

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

See tsconfig.json configuration and compiler options

ES6 (ECMA SCRIPT 6) features supported by Typescript
Compatibility chart

Compile in watchmode to constantly check for changes to the app.js file.
Run the following in one terminal

$ tsc -w

and the in another terminal start the lite-server,

$ npm start

‘let’ and ‘const’
With let we can change the variable’s value

let variable = "Tests"
console.log(variable); // output 'Tests'

variable = "thingsss"
console.log(variable); // output 'thingsss'

const num = 100;
console.log("num  = " + num);
// num = 99;// will give error as const has set this variable to constant

block scope

let variable = "thingsss";
function reset(){
  let variable = null;// this variable is independent of the variable outside this function or block scope
  console.log(variable); // outputs null
}

reset();
console.log(variable); // outputs thingss

Arrow functions
are an ES6 feature. Basic syntax,

const multiplyingNumbers1 = (number1 : number, number2: number) => number1 * number2 // automatically return a single line functions, no need for curly brackets {...}
console.log(multiplyingNumbers1(2,9));

Otherwise write it like this,

const multiplyingNumbers = (number1 : number, number2: number) => {
  return number1 * number2
}
console.log(multiplyingNumbers(2,7));

A single parameter ‘args’ can be added like this without parenthesis

const fun = args => console.log(args);
fun("Ya");

passing no parameters

const greet = () => { 
  console.log("Hello!")
}

That could be written like this

const greet1 = () => console.log("heya!");
greet();

Default parameters
Set default parameter to 10, also a second parameter ‘end’ could depend on the first parameter. Also ‘void’ means function doesn’t return anything.

const countDown = (start:number = 10, end: number = start - 5): void => { 
  while (start >0){
    start--;
  }
  console.log("Done!", start);
}
countDown();

Spread operator
To get the max of the array we use the spread operator which is three dots …
The Math.max() operator cannot take an array, but it’s elements can be spread out into a list using the spread operator.

const numbers = [1,3,25,-5];
console.log(Math.max(33, 99, 10, -3));
console.log(Math.max(...numbers));

Rest operator or parameter
Turn any number of args into an array, with three dots before the parameter,

function makeArray(...args: number[]){
  return args;
}
console.log(makeArray(1,2,3));

Other parameters can be included in the function like this, only the numbers in the array are considered, the string is ignored,

function makeArray1(name: string, ...args: number[]){//turn any number of args into an array
  return args;
}
console.log(makeArray1("Max",1,2,3));

Destructuring arrays
Giving a variable name to each element in the array.

const myHobbies = ["Cooking", "Sports"];
const [hobby1, hobby2] = myHobbies;//array to be destructured
console.log(hobby1, hobby2);

Destructuring objects

const userData = {userName: "Max", age: 27};
const {userName, age} = userData;
console.log(userName, age);

Or you could assign names other than the object’s property names, these are aliases,

const {userName : myName, age: myAge} = userData;
console.log(myName, myAge);

template literals
Similar to extended strings. Use back-ticks `…` for multi-line strings, also use template variables such as ${userName}

const userName = "Max";
const greeting = `Hello,
I am ${userName}
I'm so cool!`;
console.log(greeting);

Push an array to an existing array
Use the spread operator …

const numbers = [-3, 33, 38, 5];
console.log(Math.min(...numbers));

const newArray = [66, 2];
newArray.push(...numbers);
console.log(newArray);
// output [6, 2, -3, 33, 38, 5]

Transpile TypeScript to javaScript

TypeScript is a super set of JavaScript, brought to us by Microsoft.

Browsers can’t run TypeScript yet it is needed for Angular2+. So it is necessary to convert or ‘transpile’ your TypeScript code to JavaScript to that it will run in a browser, if you need it to run in a browser that is.

Start by intsalling typescript

$ npm install -g typescript

make a typescript file, e.g. filename.ts

let num: number = 4;

transpile with,

$ tsc filename.ts

and you’ll get a new file filename.js

var number = 4;

and that’s it!

What’s great about typescript is it gives you the errors on transpile.

Try this in your file,

console.log(blah);

without defining blah so that you get an error.

Note that the file will still run despite error showing.