【问题标题】:Typescript class composition generics打字稿类组合泛型
【发布时间】:2018-03-28 05:25:00
【问题描述】:

我正在尝试在打字稿中使用类组合。

const FoodMixin = superclass => class extends superclass {
  eat(food) {
    console.log(`Eating ${food}`);
  }
};

class Animal<T> {
  prop: T;
  constructor(public name) {
  }
}

interface Prop {}

class Dog extends FoodMixin(Animal<Prop>) {
  constructor(...args) {
    super(...args)
  }
}

我的问题是我无法将泛型传递给Animal 类。以下行引发打字稿错误:

class Dog extends FoodMixin(Animal<Prop>)

预期有 1 个参数,但得到了 2 个

我怎样才能通过泛型?

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    使用函数或构造函数作为值时不能指定类型参数的问题。

    您可以明确指定类型参数(尽管这会导致静态方法丢失:

    const FoodMixin = function <T extends new (...arsg: any[]) => any>(superclass: T) {
        return class extends superclass {
            eat(food: string) {
                console.log(`Eating ${food}`);
            }
        };
    }
    class Animal<T> {
        prop?: T ;
        constructor(public name: string) {
        }
        breathe() : void{}
    
        static mutate(): void{}
    }
    class Dog extends FoodMixin<new (name: string) => Animal<Prop>>(Animal) {
        constructor(name: string) {
            super("")
        }
    }
    
    var dog = new Dog("");
    dog.breathe();
    dog.eat("");
    dog.prop // is Prop
    Dog.mutate // error
    

    或者您可以创建一个匿名类来继承Animal 的正确实例化,然后一切都按预期工作。

    class Animal<T> {
        prop?: T ;
        constructor(public name: string) {
        }
        breathe() : void{}
    
        static mutate(): void{}
    }
    class Dog extends FoodMixin(class extends Animal<Prop>{}) {
        constructor(name: string) {
            super("")
        }
    }
    
    var dog = new Dog("");
    dog.breathe();
    dog.eat("");
    dog.prop // is Prop
    Dog.mutate // ok
    

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-29
      • 1970-01-01
      • 2018-04-27
      相关资源
      最近更新 更多