let a: number,
b: boolean,
c: string,
d: any,
e: number[] = [1, 2, 3],
f: any[] = [1, true, 'a', false];
enum Color {
Red = 0,
Green = 1,
Blue = 2,
Purple = 3,
}
let color = Color.Blue;
let message;
message = 'abc';
let length = (<string>message).length;
let altWay = (message as string).length;
interface Vector {
x: number;
y: number;
z: number;
draw: () => void;
update: (x: number, y: number, z: number) => void;
}
- Constructor initializes _x, _y variables. Question mark (?) declares the variables as optional.
- Access modifiers: public (default), private, protected.
- Using getters and setters method to provide more control.
- Exporting module Point class.
export class Point {
constructor(private _x?: number, private _y?: number) {}
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;
}
}
- Importing Point class and using the methods.
import { Point } from './point';
// Variable type of point is Point.
// Alternative way
// let point: Point = new Point(1, 2);
let point = new Point(1, 2);
point.draw(); // x = 1, y = 2
point.x; // 1
point.x = 3; // sets x = 3