2016-11-25 1 views
1

타이프 스크립트에는 다중 상속이 필요합니다. 논리적으로 많은 기능을 계층 구조에 넣는 것은 좋지 않습니다. 하나의 기본 클래스와 계층 구조 분기 수가 있습니다. 하지만 믹싱을 사용하여 몇 가지 기본 로직을 별도의 클래스에 넣어야합니다. 모든 분기에서 사용되지 않습니다. 코드 부여 됨으로써의타이프 스크립트 다중 상속

업데이트 : 여러 상속을 구현해야 할 때 현실에서

function Mixin = function(mixins:any[]){ // mixin decorator 
    return function(target){ 
     mixins.forEach((mixin) => { 
      add every function from mixing to target prototype, 
      if functions with same name does not exists there, 
      so we are able to do calls to as example different render() functions 

      Will show it in OpenableItem   
     }); 
    } 
} 

function element = function(){ 
    return function(target){ 
     target.prototype.element = function(){ 
      return this.$el; 
     } 
    } 
} 
-------------------------------------------------------------------------------------- 
@element // every item will have this function as Root as Openable 
class BaseItem{ 
    y() => number; // we need to get y position of every item 
} 
OpenableMixin{ 
    render() => render arrow only 
    open(){} => change arrow position and cause menu to fire change event 
    close(){} => change arrow position and cause menu to fire change event 
} 
class ItemsMixin extends OpenableMixing{// for now if item have childs it must be openable, 
        // but Responsive has only tasks and must be openable too 
    addItem(item: BaseItem) // need to add generics 
    removeItem(item: BaseItem) 
} 
-------------------------------------------------------------------------------------- 
@Mixin([ItemsMixin, ActivitiesMixin]) // it can have items and activities 
class OpenableItem extends BaseItem implement ItemsMixin, ActivitiesMixin { // as in typescript docs 
    render(){ 
     // call rendering from BaseItem class 
     super.render(); 
     // call rendering from OpenableMixing 
     OpenableMixin.prototype.render.call(this); 
     // do some separate rendering for OpenableItem only 
     this.$el.append('line'); 
    } 
} 

@Mixin([ItemsMixin]) // it can have items 
class RootItem extends BaseItem implement ItemsMixin{ // and subitems functionality is only for Root class 
    subitems: Array<BaseItem> // need to add generics to be able to put here different item types 
} 
-------------------------------------------------------------------------------------- 
@element 
class Menu{ 
    items: Array<Item> 
} 

@element 
class Timeline{ 
    menu: Menu 
    listAllelement() => { 
     console.log(this.element()); 
     console.log(this.menu.element()); 
     this.menu.items.forEach((item) => { 
      console.log(item.element()); 
      if(item.hasChilds()){ // really it must be (item instanceof RootItem || item instanceof OpenableItem) 
       item.items.forEach((subitem) => { // really we need some recursion here 
        console.log(subitem.element()); 
       }) 
      } 
     }) 
    } 
} 

는 드문 상황, 당신은 자바 스크립트 등의 문제가있는 때 훨씬 거의 없다. 그러나 모든 항목은 필요에 따라 다른 기능을 가질 수 있습니다.

mixins의 수를 가질 수있는 다른 항목이있을 수 있다고 상상해보십시오. 모든 것을 기초로하는 것이 현명한가? 그리고이 문제에 대한 귀하의 접근 방식은 무엇입니까?

+0

이걸로 DI를 사용해야합니다 .. – Dieterg

+0

@LenilsondeCastro 다중 상속에 대한 아이디어는 종종 OOP에서 기각되지만 실제로 어떤 원칙도 위반하지는 않습니다. 구현하기가 쉽지 않으며 우리는 어쨌든 그것은 어리석은 생각 일뿐입니다. 실제로 모든 엔티티는 많은 서로 다른 무관 한 추상화로 분류 될 수 있으며, 언어로 된 그런 종류의 구조적 조직에 대한 일등급 지원을 제공하는 것이 깔끔할 것이라고 생각합니다. – Alex

+0

@Dieterg 미안하지만 이런 상황에서 DI가 어떻게 도움이 될지 모르지만 코드 예제가 업데이트되었습니다. – Vayrex

답변

2

현재, 타이프 라이터는 다중 상속 또는 유지 mixin을 표현하는 특별한 문법을 ​​가지고 있지 않지만, 공식적인 해결 방법은 here를 찾을 수 있습니다.

이 전략은 기본적으로 기본 클래스 을 구현하고 해당 인터페이스에 간단한 더미 구현을 작성한 다음 클래스를 읽고 기본 클래스의 속성을 덮어 쓰는 특수 함수를 가지고 있습니다.

mixins/traits에서 TypeScript를 개선하기위한 몇 가지 제안 사항이 있습니다. #2919#311.

+0

고맙습니다. 그러나 나는 그 글을 읽은 후에 이곳에 왔습니다. 나는 코드 예제의 업데이트를 마쳤으며 이제 주요 질문이 변경되었습니다. – Vayrex

3

Typescript 2.2 added support for mix-ins.

+5

그리고이 사용자는이 새로운 mixin 기능을 어떻게 사용합니까? – Seanny123