Typed JavaScript at Any Scale.
on the terminal
sudo npm install -g typescript // install typescript globally
tsc -- version // checking the version
mkdir ts-hello // new folder name ts-hello
cd ts-hello // open the folder
code main.ts // open in visual studio code
tsc main.ts // compailint to javascript
ls // list of files
node main.js // execute the code in the node terminal
tsc main.ts | node main.js // compiling the file and running node
rm main.js //remove the file main.js
Variables
let name // name is valid only in the function
var name // var name can be used outside the function
types
let a: number;
let b: boolean;
let c: string;
let d: any; //diffult
let e number [] = [1, 2, 3,];
let f any [] = 1, true, 'a', false];
const colorRed = 0; // Variables defined with const behave like let variables, except they cannot be reassigned:
enum color { red = 0, Green = 1 }; //An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).
<> or as // adding type assertions to a variables
interface Point // An interface is a completely "abstract class" that is used to group related methods with empty bodies:
x?: number // var X is optional
f2 on the variable // changes the name everywhere in the code
Class: group variables (properties) and functions (methods) that are highly related.
class Point {
private x: number; // x is private - cannot change the cordinates
y: number;
draw() {
console.log('x: ' + this.x + ', Y: ' + this.y)
}
getDistance(another:Point) {
//...
}
}
let point = new Point();
point.x = 1;
point.y = 2;
point.draw();
Properties
getX() {
return this.x;
}
SetX(value0 {
if (value < 0)
throw new Error( 'value cannot be less than 0.');
this.x =value;
}
Modules
// point.ts
export class Point {
constructor(private x?: number, private y?: number) {
}
draw() {
console.log('X: ' + this.x + ', Y: ' + this.y);
}
}
// main.ts
import {Point} from './point';
let point = new Point(1, 2);
point.draw();