我有这两个代码片段如何更改它们,以便MemberModel可以作为泛型类型传递并保持不可实现,以便我可以将follow方法提取到自己的导出函数中?
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;
}
}
如何制作follow和IFollowable泛型,以便我传入的任何类型都可以像MemberModel一样保持新的状态?
答案 0 :(得分:2)
这样我传入的任何类型都可以保持新的状态,就像现在的MemberModel一样
因为在编译时擦除了typescript泛型,所以你需要明确地传递它们,例如使用如下所示的工厂:
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);
}
}