Last active
October 11, 2019 14:48
-
-
Save nunomaduro/1e37ce6fc368e7b794bbf38ca42df7a6 to your computer and use it in GitHub Desktop.
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
type ConstructorOf<TObject> = new (...input: any[]) => TObject; | |
class User { readonly name: string = 'Foo'; } | |
type HasGetName = { readonly getName: () => string; }; | |
const getName = <TUser extends ConstructorOf<User>>(Base: TUser) => { | |
return class extends Base implements HasGetName { | |
public getName() { return this.name; } | |
}; | |
}; | |
const createUser = <TUser>(methods: Function[]): TUser & User => { | |
let UserConstructor: any = User; | |
methods.forEach(method => (UserConstructor = method(UserConstructor))); | |
return new UserConstructor(); | |
}; | |
const user1 = createUser<HasGetName>([getName]); | |
alert(user1.getName()); | |
// How infer the `HasGetName` from the `getName` argument? So the user | |
// don't have to pass the generic? | |
const user2 = createUser([getName]); | |
alert(user2.getName()); // error: Property 'getName' does not exist on type 'User' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment