Skip to content

Instantly share code, notes, and snippets.

@nunomaduro
Last active October 11, 2019 14:48
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 nunomaduro/1e37ce6fc368e7b794bbf38ca42df7a6 to your computer and use it in GitHub Desktop.
Save nunomaduro/1e37ce6fc368e7b794bbf38ca42df7a6 to your computer and use it in GitHub Desktop.
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