如何扩展实现接口的TypeScript类,并将一些实现留给父类?

时间:2017-08-24 10:37:12

标签: typescript inheritance

对于长篇大论的标题感到抱歉。我正在使用ngBootstrap和UIRouter,我尝试创建public void studentsToList() { ListBox items = new ListBox(); StudentListItem roundItem = new StudentListItem(); for (int x = 0; x < students.Count; x++) { roundItem.uc_txtStudentNumber.Content += Convert.ToString(students[x].Student_Number); roundItem.uc_txtSurname.Content += Convert.ToString(students[x].Student_Name); roundItem.uc_txtSurname.Content += Convert.ToString(students[x].Student_Gender); items.Items.Add(roundItem); } } 的子类,在进入和退出时打开和关闭Ng2StateDeclaration。我可以轻松地做到这一点而不需要继承,但我会在一个更整洁的解决方案之后。

继承人我所得到的:

ngbModal

TypeScript告诉我var modalInstance:NgbModalRef; class ModalStateDeclaration implements Ng2StateDeclaration { name:string; url:string; onEnter(transition: Transition, state: Ng2StateDeclaration) { modalInstance = modalService.open(SomeComponent); for (var key in transition.params()) { modalInstance.componentInstance[key] = transition.params()[key]; } var currentState = transition.from().name; modalInstance.result.catch(function(reason) { if (currentState) { window.history.back(); } else { stateService.go('home'); } }); } onExit() { modalInstance.close(); } } export const modalBookState:ModalStateDeclaration = { name: 'modalBookState', url: '/b/:id' }; 缺少modalBookStateonEnter。如何使用onExit中的onEnteronExit实施?我是否需要使用ModalStateDeclaration实现它们?

2 个答案:

答案 0 :(得分:0)

最简单的方法是新建类而不为其分配对象文字,并向类中添加构造函数

class ModalStateDeclaration implements Ng2StateDeclaration {
    constructor(public name:string, public url:string) {} 
    ...
}
// The type annotation is optional you could remove :ModalStateDeclaration, I left it in for clarity
export const modalBookState:ModalStateDeclaration = new ModalStateDeclaration('modalBookState', '/b/:id');

如果你真的想创建一个对象文字而不是实例化你的类,你可以这样做:

export const modalBookState:ModalStateDeclaration = {
    onEnter: ModalStateDeclaration.prototype.onEnter,
    onExit: ModalStateDeclaration.prototype.onExit,
    name: 'modalBookState',
    url: '/b/:id'
};

答案 1 :(得分:0)

我建议不要直接使用对象文字,或者除new ModalStateDelcaration(...)以外的任何文件,因为它会在运行时检查instanceof失败。

我会做这样的事情:

const modalBookStateOptions: Partial<ModalStateDeclaration> = {
  name: 'modalBookState',
  url: '/b/:id'
}

类型Partial<ModalStateDeclaration>表示modalBookStateOptions具有 ModalStateDeclaration属性的部分。 (TypeScript Handbook如果您想要阅读更多内容,则会提及Partial<T>

然后,您可以通过将部分对象合并到类的新实例中来创建实际的ModalStateDeclaration

export const modalBookState: ModalStateDeclaration = Object.assign(new ModalStateDeclaration, modalBookStateOptions);

还有其他方法可以做到这一点(@Titian提供了一些其他选项),但这就是我如何去做。

祝你好运!