Last active
February 6, 2018 14:20
-
-
Save hraban/79d3c4ae3fdba9ba1a810509b13d613b to your computer and use it in GitHub Desktop.
Typescript runtime mixins
This file contains 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
// 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