Skip to content

Instantly share code, notes, and snippets.

@umayr
Created August 29, 2016 19:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umayr/2e8ba3fb728ffe8cb448bed8ee499faa to your computer and use it in GitHub Desktop.
Save umayr/2e8ba3fb728ffe8cb448bed8ee499faa to your computer and use it in GitHub Desktop.
An Interface example for TypeScript
interface IFunc {
(n: number[]): number;
}
interface IOperations {
add: IFunc;
sub: IFunc;
mul: IFunc;
div: IFunc;
}
interface IClass {
operations: IOperations;
perform(operator: string, ...args: number[]): number;
}
class Calc implements IClass {
operations: IOperations;
constructor(operations: IOperations) {
this.operations = operations;
}
perform(operator: string, ...args: number[]): number {
switch (operator) {
case '+': return this.operations.add(args);
case '-': return this.operations.sub(args);
case '*': return this.operations.mul(args);
case '/': return this.operations.div(args);
}
}
}
let c = new Calc({
add: (n: number[]): number => n.reduce((p: number, c: number): number => p + c, 0),
sub: (n: number[]): number => n.slice(1).reduce((p: number, c: number): number => p - c, n[0]),
mul: (n: number[]): number => n.reduce((p: number, c: number): number => p * c, 1),
div: (n: number[]): number => n.slice(1).reduce((p: number, c: number): number => p / c, n[0]),
})
alert(c.perform('+', 10, 21, 37, 42)); // 10 + 21 + 37 + 42 = 110
alert(c.perform('-', 97, 2, 13, 25)); // 97 - 2 - 13 - 25 = -137
alert(c.perform('*', 48, 1, 34, 72)); // 48 * 1 * 34 * 72 = 117504
alert(c.perform('/', 81, 3, 4)); // 81 / 3 / 4 = 6.75
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment