Skip to content

Instantly share code, notes, and snippets.

@hraban
Last active February 6, 2018 14:20
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 hraban/79d3c4ae3fdba9ba1a810509b13d613b to your computer and use it in GitHub Desktop.
Save hraban/79d3c4ae3fdba9ba1a810509b13d613b to your computer and use it in GitHub Desktop.
Typescript runtime mixins
// Inspired by:
// https://github.com/tc39/proposal-pipeline-operator/blob/37119110d40226476f7af302a778bc981f606cee/README.md#object-decorators
//
// Once pipe operator is implemented in TS, use this example to check if it
// survives type checking.
// Describe mixed in functionality
interface Foo {
foo(): number;
}
interface Bar {
bar(): string;
}
// This is typechecked. Try changing e.g. the spelling of `foo`, or `3` into
// `"yes"`.
function mixinFoo<T>(x: T): T & Foo {
return Object.assign(x, {foo: function() { return 3; }});
}
// This is typechecked, too. Note the factory is not generic, but the returned
// function is.
function mixinBarFactory(msg: string) {
return function mixinBar<T>(x: T): T & Bar {
return Object.assign(x, {bar: function() { return msg; }});
};
}
// Random type to prove the point
class Something {}
function mixinTest(x: Something) {
const y = mixinBarFactory("hello")(mixinFoo(x));
y; // Check my type!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment