Typescript: How to extend two classes?

前端 未结 9 1109
猫巷女王i
猫巷女王i 2020-11-29 22:38

I want to save my time and to reuse common code across classes which extends PIXI classes (a 2d webGl renderer library).

Object Interfaces:

9条回答
  •  情书的邮戳
    2020-11-29 23:29

    A very hacky solution would be to loop through the class you want to inherit from adding the functions one by one to the new parent class

    class ChildA {
        public static x = 5
    }
    
    class ChildB {
        public static y = 6
    }
    
    class Parent {}
    
    for (const property in ChildA) {
        Parent[property] = ChildA[property]
    }
    for (const property in ChildB) {
        Parent[property] = ChildB[property]
    }
    
    
    Parent.x
    // 5
    Parent.y
    // 6
    

    All properties of ChildA and ChildB can now be accessed from the Parent class, however they will not be recognised meaning that you will receive warnings such as Property 'x' does not exist on 'typeof Parent'

提交回复
热议问题