Skip to content

Instantly share code, notes, and snippets.

@robertleeplummerjr
Created October 28, 2017 22:13
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save robertleeplummerjr/70625e6ba23adf05464ea02fedbb30a9 to your computer and use it in GitHub Desktop.
Dynamic Class Hierarchy in Typescript
class Item {
public static async get<Options extends { id: string }>(o: Options, api: Api): Promise<Item> {
return new Promise<Item>((accept, reject) => {
console.log(api);
accept(new Item());
});
}
public static async search<Options extends { query: string }>(o: Options, api: Api): Promise<Item[]> {
return new Promise<Item[]>((accept, reject) => {
console.log(api);
accept([new Item()]);
});
}
public static async delete<Options extends { id: string }>(o: Options, api: Api): Promise<void> {
}
public static async create<Options extends Item>(item: Item, api: Api): Promise<Item> {
return null;
}
public id: string;
public name: string;
}
class StaticBridge {
public static build<T>(Type: T, c: Api): any {
return Object.getOwnPropertyNames(Type)
.filter((prop) => typeof Type[prop] === "function")
.reduce((methods, method) => ({
// tslint:disable-next-line:no-any
...methods as any,
[method]: async (v: any): Promise<any> => {
return Type[method](v, c);
},
}), {});
}
}
class Api {
public get Item(): any {
return StaticBridge.build(Item, this);
}
}
const api = new Api();
api.Item.get({ id: "string" })
.then((item: Item) => {
console.log(item);
});
api.Item.search({ query: "string" })
.then((items: Item[]) => {
console.log(items);
});
api.Item.create(new Item());
api.Item.delete({ id: "string" });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment