Skip to content

Instantly share code, notes, and snippets.

@yosiat
Last active July 9, 2021 10:43
Show Gist options
  • Save yosiat/486be3287e1bb7e8f84bcdb72a72643c to your computer and use it in GitHub Desktop.
Save yosiat/486be3287e1bb7e8f84bcdb72a72643c to your computer and use it in GitHub Desktop.
// extra constraint
function action<TContext extends MyContext>(handler: (arg: TContext) => void): Function {
return function (object: object, aub: any, descriptor: any) {
if (!object.hasOwnProperty('getContext')) {
throw new Error("Can't bind @action to class which don't implement 'getContext' method");
}
// @ts-ignore
const ctx = object.getContext();
console.log(`listening to: ${handler(ctx)}`);
};
}
interface ContextProvider<T> {
getContext(): T;
}
type MyContext = {
some_id: number;
};
class Controller implements ContextProvider<MyContext> {
@action(ctx => `event:${ctx.some_id}`)
public eventHandler(message: any) {
console.log('My event handler', message);
}
getContext(): MyContext {
return { some_id: 6 };
}
}
type AnotherContext = { another_id: number };
class Controller2 implements ContextProvider<AnotherContext> {
// This shouldn't compile, since context here is `AnotherContext` and it doesn't have `some_id` property on it
@action(ctx => `event:${ctx.some_id}`)
public eventHandler(message: any) {
console.log('My event handler', message);
}
getContext(): AnotherContext {
return { another_id: 6 };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment