打字稿多重继承

时间:2016-11-25 15:04:33

标签: typescript multiple-inheritance

我需要在打字稿中进行多重继承。 从逻辑上讲,将很多功能放到层次结构中并不好。 我有一个基类和层次结构分支数。 但我需要以某种方式使用混合将一些主要逻辑放在单独的类中,因为它不会在每个分支中使用。

代码例外更新:

    getRequestAndCheckStatus("https://aaaaaaa.io/api/v1/aaaaaaaaa", MyPOJO[].class,                    
                             Collections.singletonList(MediaType.APPLICATION_JSON_UTF8), 
                             new HashMap<String, String>(){{ put("API-Key", "4444444-3333-2222-1111-88888888"); }}), 
                             new HashMap<String, Object>(){{ put("Date", "2015-04-04"); }});

实际上,当您需要实现多重继承时,这种情况很少见,而且当您在javascript中遇到此类问题时很少见。但是每个项目都可以根据需要具有不同的功能。

想象一下,可以有不同的项目可以有多个mixin。把一切都放到基地是明智的吗?你对这个问题有什么看法?

3 个答案:

答案 0 :(得分:9)

目前,TypeScript没有任何特殊语法来表达多重继承或mixins,但可以找到官方解决方法here

该策略基本上是让你的主类实现你想要的类,为它们的接口编写简单的虚拟实现,然后有一个特殊的函数来读取你的类并覆盖属性你的主要班级。

有一些建议可以让mixScript在mixins / traits上更好,例如。 #2919#311

答案 1 :(得分:8)

@ kjetil-klaussen是正确的,打字稿2.2添加了对ECMAscript 2017 mixin pattern的支持

这是完整的代码示例:

// http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/
// https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#support-for-mix-in-classes

type Constructor<T> = new (...args: any[]) => T;

class S {
  foo() {
    console.log('foo from S');
  }
}

// Here the possible SuperClass is set to {} (Object)
function Mixin1<T extends Constructor<{}>>(SuperClass: T) {
  return class extends SuperClass {
    foo() {
      console.log('foo from Mixin1');
      if (super.foo) super.foo();
    }
  };
}

// Here the possible SuperClass (S) is specified
function Mixin2<T extends Constructor<S>>(SuperClass: T) {
  return class extends SuperClass {
    foo() {
      console.log('foo from Mixin2');
      super.foo();
    }
  };
}

class C extends Mixin1(Mixin2(S)) {
  foo() {
    console.log('foo from C');
    super.foo();
  }
}

new C().foo();

这将输出:

foo from C
foo from Mixin1
foo from Mixin2
foo from S

答案 2 :(得分:4)

Typescript 2.2添加了support for mix-ins