Wendell Muntslag Wendell Muntslag - 2 months ago 5
TypeScript Question

How to make a generic type constraint instanciable

I have these two code fragments how can I change them so that MemberModel can be passed in as generic type and remains instanciatable so that I can extract the follow method into its own exported function?

export interface IFollowable {
follow(user: IUserModel): IMemberModel;
}

export class CardModel implements ICardModel, IFollowable {
public follow(user: IUserModel): IMemberModel {
let member = new MemberModel({userId: user.id});
member.role = UserRoles.follower;
this.members.push(member);
return member;
}
}


How do I make follow and IFollowable generic so that the whatever type I pass in remains newable like the MemberModel is right now?

Answer

so that the whatever type I pass in remains newable like the MemberModel is right now

Because typescript generics are erased at compile time you need to pass them in explicitly e.g. using a factory as shown below:

type User = {name:string};
type Member = {name: string};
type MemberCreator = {new (user:User): Member};

interface Followable {
    follow(user: User, memberCreator: MemberCreator): Member;
}

export class CardModel implements Followable {
    public follow(user: User, memberCreator: MemberCreator): Member {
       return new memberCreator(user);
    }
}
Comments