From b9e22951af66b99cf3f9d34b483edb4a285c6628 Mon Sep 17 00:00:00 2001 From: Cuong Nguyen Date: Sat, 8 Dec 2018 21:37:14 +0200 Subject: [PATCH] Added Typescript/Mixin (#26256) --- guide/english/typescript/mixin/index.md | 28 +++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 guide/english/typescript/mixin/index.md diff --git a/guide/english/typescript/mixin/index.md b/guide/english/typescript/mixin/index.md new file mode 100644 index 0000000000..0e6532918c --- /dev/null +++ b/guide/english/typescript/mixin/index.md @@ -0,0 +1,28 @@ +--- +title: Mixin +--- +## Mixin + +In TypeScript, making a mixin is quite tricky due to its static typing. A good solution for mixin is to make a function receives a class and return a new class, which is similar to a higher-order function. + +```typescript +type Constructor = new (...args: any[]) => T; + +class User { + constructor(name: string) { + this.name = name + } +} + +function Loggable(Base: ClassBase) { + return class extends Base { + constructor(...args: any[]) { + super(...args) + console.log(`arguments: ${args}`) + } + } +} + +const LoggableUser = Loggable(User) +const someUser = new LoggableUser('John Doe') +``` \ No newline at end of file