Skip to content

Instantly share code, notes, and snippets.

@jednano
Last active February 22, 2019 20:44
Show Gist options
  • Save jednano/74d07dfda5101ff75e6e702bfe49d3e9 to your computer and use it in GitHub Desktop.
Save jednano/74d07dfda5101ff75e6e702bfe49d3e9 to your computer and use it in GitHub Desktop.
Hooks
import { createNinja, Katana, Shuriken } from './entities';
export default {
Warrior: createNinja,
Weapon: () => new Katana(),
ThrowableWeapon: () => new Shuriken(),
};
import hook from './hook';
import { ThrowableWeapon, Warrior, Weapon } from './interfaces';
export class Katana implements Weapon {
public hit() {
return 'cut!';
}
}
export class Shuriken implements ThrowableWeapon {
public throw() {
return 'hit!';
}
}
export function createNinja() {
const [
weapon,
throwableWeapon,
] = hook<[Weapon, ThrowableWeapon]>('Weapon', 'ThrowableWeapon');
return class Ninja implements Warrior {
public fight() {
return weapon.hit();
}
public sneak() {
return throwableWeapon.throw();
}
}
}
import config from './config';
export default function hook<T extends any[]>(...keys: string[]) {
return keys.map(key => config[key]) as T;
}
export interface Warrior {
fight(): string;
sneak(): string;
}
export interface Weapon {
hit(): string;
}
export interface ThrowableWeapon {
throw(): string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment