Created
October 28, 2017 22:13
-
-
Save robertleeplummerjr/70625e6ba23adf05464ea02fedbb30a9 to your computer and use it in GitHub Desktop.
Dynamic Class Hierarchy in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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