TypeScript is a super set of JavaScript. It adds static typing to JavaScript. TypeScript is compiled to JavaScript.
- Install the typescript dependency by running
yarn
in this folder - Run
yarn build
to compile the typescript file to javascript - Run
node index.js
to run the compiled application
This codebase demonstrates how the TypeScript compiler tsc
compiles index.ts
(using modern JavaScript syntax)
type Person = {
name: string;
age?: number;
};
const person1 = {
name: "Andre",
age: 16,
};
const getPersonDetails = (person: Person) => {
return person.age !== undefined
? `${person.name}: ${person.age} years`
: person.name;
};
console.log(getPersonDetails(person1));
into the following JavaScript file index.js
(ECMAScript version 3 - published in December 2009):
"use strict";
var person1 = {
name: "Andre",
age: 16
};
var getPersonDetails = function (person) {
return person.age !== undefined
? "".concat(person.name, ": ").concat(person.age, " years")
: person.name;
};
console.log(getPersonDetails(person1));
Running yarn build-and-run
combines two commands which do the following:
tsc --project .
: Run the TypeScript compilertsc
to compileindex.ts
(TypeScript) toindex.js
(JavaScript).node index.js
: The node scriptindex.js
is then directly run in the command line.
- In
tsconfig.json
change"target": "ES3",
to"target": "ES6",
- Run the
build-and-run
script (i.e.yarn build-and-run
) - Which differences do you observe in
index.js
?
- In
index.ts
add the following enum:
enum Lang {
"en",
"de",
"zh",
}
const lang = Lang.en;
- Run the
build
script (i.e.yarn build
); - What appeared in
index.js
?