Skip to content

Instantly share code, notes, and snippets.

@hraban hraban/runtime-mixin.ts
Last active Feb 6, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.