2016-09-19 67 views
1

我有這兩個代碼片段如何更改它們,以便MemberModel可以作爲泛型傳遞並保持instanciatable,以便可以將後續方法提取到其自己的導出函數中?如何使通用類型約束實例化

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; 
    } 
} 

我該如何使跟隨和IFollowable泛型,以便我傳入的任何類型保持新的像現在的MemberModel?

回答

2

從而使任何類型的我通過在保持newable像MemberModel是現在

因爲打字稿泛型是在編譯時刪除你需要傳遞他們明確如使用如下所示的工廠:

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); 
    } 
}