ES6: Interface
interface Person {
firstname?: string, // optional parameter with `?`
lastname: string
}
function greeter(person: Person) {
return 'Hello, ' + person.firstname + ' ' + person.lastname;
}
var user = { firstname: "Jane", lastname: "User" };
document.body.innerHTML = greeter(user);
// Function types
interface SearchFunc {
(source: string, subString: source): boolean;
}
var mySearch: SearchFun;
mySearch = function (src: string, sub: string) {
var result = src.search(sub);
if (result == -1) {
return false;
} else {
return true;
}
}
// Array types
interface StringArray {
[index: number]: string; // index can have `string` or `number` type
}
var myArray: StringArray;
myArray = ['Bob', 'Fred'];
// Class types
interface ClockInterface {
currentTime: Date;
setTime(d: Date);
}
class Clock implements ClockInterface {
currentTime: Date;
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) { }
}
// =======================
interface ClockStatic {
new (hour: number, minutes: number) {}
}
class Clock {
currentTime: Date;
constructor(h: number, minutes: number) {}
}
var cs: ClockStatic = Clock;
var newClock = new cs(7, 30);
// Extending interface
interface Shape {
color: string;
}
interface PenStroke {
penWidth: number;
}
interface Square extends Shape, PenStroke {
sideLength: number;
}
var square = <Square>{};
square.color = 'blue';
square.sideLength = 10;
square.penWidth = 5.0;
// Hybrid Types
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
var c: Counter;
c(10);
c.reset();
c.interval = 5.0;