Skip to content

Instantly share code, notes, and snippets.

@rbuckton
Last active March 27, 2019 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbuckton/65916a9e9cc35f77b9d8a2a57c495642 to your computer and use it in GitHub Desktop.
Save rbuckton/65916a9e9cc35f77b9d8a2a57c495642 to your computer and use it in GitHub Desktop.

Decorators, Take 4

A decorator is a function that returns a series of "hooks":

function dec() {
  return [
    { register(klass) { } },
    { register(target, key) { } },
    { wrap(f) { return f; } },
    { initialize(target, key, value) { } },
    { expose(target, key, get, set) { } },
  ];
}

A "hook" is an object with one or more "hook methods" and an optional for filter:

type DecoratorHook =
  | { register(klass: Function): void, for?: "class" }
  | { register(target: object, key: string | symbol): void, for?: "method" }
  | { wrap(f: Function): Function, for?: "class" | "method" }
  | { initialize(instance: object, key: string | symbol, value: unknown): void, for?: "field" }
  | { expose(
        target: object,
        key: string | symbol, 
        get: (instance: object) => unknown, 
        set: (instance: object, value: unknown) => void
      ): void,
      for?: "method" | "field"
    };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment