Home > Back-end >  How can I send an object from a subclass to the superclass in TypeScript?
How can I send an object from a subclass to the superclass in TypeScript?

Time:09-10

I have an object in the superclass Enemy

interface rigidBodyData{
    spriteName: string
    spriteSizeX: number
    spriteSizeY: number
    idleAnim: string
    mass: number
}

And I import it to the subclass

import rigidBodyData from "./Enemy"
export default class Crabby extends Enemy{
    public rigidBody: Phaser.Physics.Arcade.Sprite
    private dataList: rigidBodyData

    constructor(_scene:Phaser.Scene, x:number, y:number){
        super(_scene, x, y, this.dataList)
    }

How can I create an modifiable object of type tigidBodyData and return it to the superclass?

I don't want to send the parameters in the Crabby object declaration this.crabby = new Crabby(this, 150, 650)

I tried to send a tuple instead an object, but doesn't work, so, I'm trying to send an object

CodePudding user response:

I advice you to if you not going to have sub implementations for rigidBodyData class change it to

  export class RigidBodyData{
    spriteName: string
    spriteSizeX: number
    spriteSizeY: number
    idleAnim: string
    mass: number
  }

And you do not need to pass data to super class. You can simply access its properties from child class

  export class Enemy{
        private enemyData: RigidBodyData;
  }

  export default class Crabby extends Enemy{
        public rigidBody: Phaser.Physics.Arcade.Sprite
        private dataList: RigidBodyData
    
        constructor(_scene:Phaser.Scene, x:number, y:number){
           this.enemyData = new RigidBodyData();
           // or 
           this.enemyData = here add the things you want to assign;
        }
    }

Else you can implement a constructor in Enemy and then pass via constructor

export class Enemy{
        private enemyData: RigidBodyData;
        constructor(data: RigidBodyData){
           this.enemyData = data;
        }
  }

  export default class Crabby extends Enemy{
        public rigidBody: Phaser.Physics.Arcade.Sprite
        private dataList: RigidBodyData

        constructor(_scene:Phaser.Scene, x:number, y:number){
           const newData = new RigidBodyData()
           // map the properties
           super(newData);
        }
    }
  • Related