TypeScript class interface
TypeScript class
JavaScript doesn’t have class idea.
TypeScript has.
Finally, TypeScript compiles Javascript. It becomes prototype.
Example
class Helo {
message: string;
constructor(message: string) {
this.message = message;
}
sayHello() {
return "Hello, " + this.message;
}
}
Use this
let greeter = new Helo("Erichi");
console.log(greeter.message); // Can access
console.log(greeter.sayHello());
private, protected, public
We can use access attr like other language
class Employee {
private name: string; // private, protected, private
constructor(theName: string){
this.name = theName;
}
}
Other Sample
class Animal {
name: string;
constructor(theName: string) {
this.name = theName;
}
run(kilo: number = 1) {
console.log(`${this.name} run ${kilo}`)
}
}
var anim = new Animal("lion");
anim.run();
class Bear extends Animal {
constructor(name: string) {
super(name);
}
run(kilo: number = 5) { //public, private
super.run(kilo);
}
}
Interface
TypeScript has interface like Java, C#
interface ClockInterface {
currentTime: Date; // no let
setTime(d: Date);
}
class Clock implements ClockInterface {
currentTime: Date;
//let num: number; Error
constructor(h: number, m: number){}
setTime(d: Date) {
this.currentTime = d;
}
}
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getCounter(): Counter {
let counter = <Counter>function (start: number) { };
counter.interval = 123;
counter.reset = function () { };
return counter;
}
Implements more than 2 interfaces
interface M1 {
lost();
}
interface M2 {
play();
}
class M3 implements M1, M2 {
lost() {
}
play() {
}
}
Reverse!!
interface can extend class
class Base {
private state: any;
}
interface Next extends Base {
}
interface Next2 extends Next {
}
Abstract
We can also use abstract
abstract class Player {
abstract hit(): void;
play(): void {
console.log("Ball");
}
}
class NormalPlayer extends Player {
hit(): void {
console.log("I am normal player");
}
}
static
class Grid {
static origin = {x:0, y:0};
}
console.log(Grid.origin);
