Conditional inheritance in Typescript involves creating classes that inherit from

My objective is to develop a prototype that can extend various classes. I am tasked with creating a class that extends either Mesh or Points of THREE.js. The subclass I have created is identical for both scenarios and cannot be an interface.

class PointsElement extends THREE.Points {
  public name: string
  protected width: number
  protected height: number

  constructor (protected target: THREE.Scene | THREE.Group, protected properties: IElementProperties) {
    super()
    this.name = this.properties.name
    AutoBind(this)
  }

  public async preload () {
  }

  public async show () {
    this.target.add(this)
  }

  public async hide () {
    this.target.remove(this)
  }
}

class MeshElement extends THREE.Mesh {
  public name: string
  protected width: number
  protected height: number

  constructor (protected target: THREE.Scene | THREE.Group, protected properties: IElementProperties) {
    super()
    this.name = this.properties.name
    AutoBind(this)
  }

  public async preload () {
  }

  public async show () {
    this.target.add(this)
  }

  public async hide () {
    this.target.remove(this)
  }
}

My goal is to optimize the code by removing the 'Element' suffix, as the content remains the same in MeshElement and PointsElement, despite each class extending different base classes.

Answer №1

Although it may seem a bit rushed and rough, I hope the concept of a factory pattern comes across clearly.

Your explanation represents just one approach to implementing a factory, not necessarily the only one.

enum Shapes {
  Square = "Square",
  Circle = "Circle"
}

class Shape {
  public isShape = true;
}

class Square extends Shape {
  public type = Shapes.Square;
}

class Circle extends Shape {
  public type = Shapes.Circle;
}

class ShapeFactory<T extends Shapes> {
  private shapesMap = new Map<Shapes, typeof Square | typeof Circle>([
    [Shapes.Square, class Geometry extends Square {}],
    [Shapes.Circle, class Geometry extends Circle {}]
  ]);

  constructor(private type: Shapes) {}

  public getGeometry(): T extends Shapes.Square ? typeof Square : typeof Circle {
    const geometry = this.shapesMap.get(this.type);
    if (geometry) {
      return <T extends Shapes.Square ? typeof Square : typeof Circle>geometry;
    }
    throw new Error(`Invalid shape type ${this.type}`);
  }
}

const MySquare = new (new ShapeFactory<Shapes.Square>(Shapes.Square).getGeometry())();
console.log(MySquare.type);

const MyCircle = new (new ShapeFactory<Shapes.Circle>(Shapes.Circle).getGeometry())();
console.log(MyCircle.type);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing CSS styles on freshly added elements

When dynamically adding an element to a parent div, I encounter an issue where the styles defined in my CSS are not applied to the newly added element. $('.some_div').append("<li class='hi'>hey!</li>") Although I can manua ...

display the information stored within the sports attribute using React

I am attempting to display the values stored in the sports property. So, I inserted a console log within the sports property. However, an error is being thrown: Syntax error: C:/codebase/src/containers/sports.js: Unexpected token, expec ...

Using jQuery to transform a JSON array within a JSON object into an array

I am attempting to convert the JSON data below: { "questions": [ { "question#1": "How much is 3+1", "correct answer": 1, "answers": { "ans#1": "5", "ans#2": "4", ...

Scaling texture to fit on a plane in THREE.js

I am attempting to 'fit-to-scale' a mapped image texture on a single plane, aiming to simulate the behavior of object-fit:cover. The image map needs to scale proportionally in order to cover the entire plane completely. I have experimented with ...

What is the best way to send parameters back to the backend in Spring Boot?

In the service below, I am passing 2 parameters from the front end: uploadFile(fileName: string, fileAsBase64:string): Observable<any> { let params = new HttpParams(); params = params.append('fileName', fileName); params=params. ...

Create a function that iterates through an array to find the indexes of elements that meet a specific condition simultaneously

Imagine having an array of random numbers with a length of n. I am looking to develop a function that can iterate through the array and identify two (or more) indices that meet a specific criteria simultaneously. For example: const arr = [12, 10, 2, 3, 1 ...

Leveraging a library sibling folder container for collaborative package sharing

I am working with multiple applications stored in a mono git repository and I am looking to incorporate shared libraries across them. Below is my current directory structure: . ├── libs │   └── messages | ├── package.json | ...

Although req.user is undefined, the login process is functioning properly

Solution Quest This inquiry has been posed countless times, yet none of the responses have resolved my issue. In all my app's routes, the req.user call consistently returns undefined, regardless of which route I access. Interestingly, my login funct ...

The rendering of THREE.PlaneGeometry does not appear on the screen

After following the tutorial from aerotwist and successfully implementing the code, I encountered an issue when experimenting with THREE.PlaneGeometry. Here is the code snippet: var $container = $('#container'); var WIDTH = $container.width(), H ...

What is the reason for the 'scrollHeight' being considered 'undefined' in this particular scenario, and why did the iframe encounter an error when switching to the html-file?

This is my first time asking a question, so please forgive any mistakes... I am attempting to create a website using HTML, CSS, and JavaScript on my Raspberry Pi with Apache2. I have written a script for an automatic iframe height function based on the co ...

Attempting to reposition a button through JavaScript functions

Need help with a school project: When the user clicks the initial login button, it should be removed and replaced by a new button that descends 100 pixels over a 2-second period. I'm looking for a more efficient way to achieve this, any assistance wou ...

Troubles with Vue.js when retrieving URL data from API

How can I properly display multiple store URLs from an API in separate lines? Here is my vue code: <a v-bind:href=“storeUrl”> {{storeUrl}} </a> And here is my script: .... computed:{ storeUrl() { return this.games.store.map(({{url}}) => ...

I'm stuck trying to figure out all the parameters for the MapsPage component in Angular 2

Currently, I am utilizing Angular2 with Ionic2 for my mobile app development. Everything was working flawlessly until I decided to incorporate a new module for Google Maps navigation. Specifically, I am using phonegap-launch-navigator for this purpose. The ...

What are some solutions for resolving JavaScript's 'undefined' error?

(function(window) { var johnGreeter = {}; johnGreeter.name = "John"; var greeting = "Hello "; johnGreeter.sayHello = function() { console.log(greeting + johnGreeter.name); } window.johnGreeter = johnGreeter; })(window); // <!DOCTYPE html ...

Tips for boosting the efficiency of replaceWith on Internet Explorer 11

When rendering an array of data in a table element, there is a need for the table to be updated with new data as it can be filtered dynamically. However, I have encountered a performance issue specifically on IE11 when trying to render 1700 data entries us ...

Having trouble with iterating through nested array objects in Angular 4 component

I am facing an issue when attempting to iterate over a nested array object using the code below. It seems to be throwing an error saying "undefined". Could this be related to Typescript or angular4? import { Process, Event } from "./process"; export clas ...

Search for styling cues within the text and transform them into distinct elements

I was inspired to develop a unique text editor that utilizes cues within the text, such as :strong:, to set formatting rules. Here is the code snippet I have so far: <?php $document = $_GET["document"]; $user = $_GET["user"]; if ($user != n ...

ISO format for the number of weeks in a month, considering weeks that cross over Thursday

I am looking for a precise number of weeks per month in accordance with the ISO standard. Instead of using JavaScript's Date, I am utilizing momentJS. According to the ISO date format, a month's week count is determined based on whether it cont ...

A guide to building your own live HTML editing tool

I'm currently developing a PHP website that allows users to enter text into a textarea, and have the input displayed in a table in real time for a preview of the result. I am seeking guidance on how to make this feature possible. I have come across w ...

Node-express can seamlessly switch between multiple databases dynamically

After extensive searching for a solution to my problem, I have come up empty-handed. If anyone has experience in similar situations, your help would be greatly appreciated. I have developed an application server in Node Express with MySQL as the database. ...