27. TypeScript && JavaScript Fundamentals
- Strong/static typing
- Interfaces, access modifiers public, private, protected
- Fields, properties, generics, enums, types
- Catch errors at compile time instead of runtime
- Code completion in editors
- TypeScript transpiles to JavaScript, any valid JavaScript Code is valid TypeScript Code(is this true?)
Block scoped variables (JavaScript):
function doSomething() {
for (let i = 0; i < 10; i++) {
console.log(i);
}
const myConstant = 10;
console.log(myConstant);
}
doSomething();
Types:
let a: number;
let b: boolean;
let c: string;
let d: any;
let e: number[];
let f: boolean[];
let g: string[];
let h: any[] = [1, true, 'abc'];
enum Color { Red, Green, Blue };
let color = Color.Red;
Type Assertions:
let message;
message = 'xyz';
let z = (<string>message).indexOf('z');
let y = (message as string).indexOf('y');
Arrow Functions (JavaScript):
let log = function(message) {
console.log(message);
}
let doLog = (message) => console.log(message);
log('hello');
doLog('world');
Interfaces:
interface Point {
x: number,
y: number
}
let drawPoint = (point: Point) => { }
drawPoint({
x: 1,
y: 2
})
Classes (JavaScript):
class Point {
x: number;
y: number;
draw() { }
getDistance(another: Point) { }
}
Objects (JavaScript):
class Point {
x: number;
y: number;
draw() { console.log(`X: ${this.x}, Y: ${this.y}`); }
getDistance(another: Point) { }
}
let point = new Point();
point.x = 2;
point.y = 3;
point.draw();
Constructors (JavaScript) Access Modifiers in Constructor Parameters (TypeScript):
class Point {
constructor(private x?, private y?) {}
draw() { console.log(`X: ${this.x}, Y: ${this.y}`); }
}
let point = new Point(4, 5);
point.draw();
Properties (JavaScript):
class Point {
constructor(private _x?, private _y?) {}
draw() { console.log(`X: ${this._x}, Y: ${this._y}`); }
get x() {
return this._x;
}
set x(value) {
if (value < 0) {
throw new Error('value cannot be less than 0.');
}
this._x = value;
}
}
Modules (JavaScript):
export class Point {
constructor(private _x?, private _y?) {}
draw() { console.log(`X: ${this._x}, Y: ${this._y}`); }
}
import { Point } from './point';
let point = new Point(3, 4);
point.draw();