Incorporate new class into preexisting modules from external library

I am currently working on expanding Phaser by incorporating a new module called Phaser.Physics.Box2D. While Phaser already utilizes this module internally, it is an additional plugin and I am determined to create my own version.

TypeScript is the language of choice for my project, and I want to ensure that I extend Phaser properly. After some searching, I came across an interesting issue that provides guidance on adding a new definition (interface), but lacks information on implementing code.

Below is my attempt at extending Phaser using TypeScript:

// This section contains phaser typescript definitions
// The code I am trying to incorporate can be found at the end.
// Feel free to try it out on https://www.typescriptlang.org/play/index.html
declare module "phaser-ce" {
    export = Phaser;
}

declare class Phaser {
    static VERSION: string;
    static DEV_VERSION: string;
    static GAMES: Phaser.Game[];
}

declare module Phaser {
    enum blendModes {

        NORMAL,
        ADD,
        MULTIPLY,
        SCREEN,
        OVERLAY,

    }

    // Additional classes like Animation, Signal, and Game are defined here...

    class Physics {

        constructor(game: Phaser.Game, config?: any);

        static ARCADE: number;
        static P2JS: number;
        static NINJA: number;
        static BOX2D: number;
        static CHIPMUNK: number;
        static MATTERJS: number;

        // Various physics implementations such as arcade, ninja, and p2 are included here.

        box2d: any; // I aim to customize this, open to suggestions!

    }

    module Physics {

        class Arcade {

        }

        // Other physics modules like Ninja and P2 are defined similarly...

    }
}

// My goal is to introduce a new class in the Physics module...
class MyAwesomeWork {
    constructor(greet: string) {
        console.log(greet);
    }
}

declare module Phaser {
    module Physics {
        class Box2D {

        }
        module Box2D {
            // ... Unfortunately, this approach did not work :(
            class Body {

            }
        }
    }
}

Phaser.Physics.Box2D = MyAwesomeWork;

Answer №1

It is not recommended to directly alter or extend external packages, as any modifications made may be overwritten when the module is updated. Unfortunately, altering a library directly is not possible.

To work around this issue, many developers create their own enhancements and wrappers within their source code. This approach ensures that any customizations remain unaffected by new npm install commands.

This practice is applicable not only to TypeScript but also to JavaScript. The reason why you can extend types on your own is due to the fact that not all packages are typed, and for static typing purposes, TS assumes your expertise. Moreover, these types do not impact the final compiled code. However, when it comes to executable code, both TS and JS defer to the library author's implementation, necessitating that any personal changes be integrated into your own codebase.

Answer №2

Check out the resolved answer below

import 'phaser-ce';

declare global {
    module Phaser {
        module Physics {
            class Box2D {
                value: number;
                // The constructor declaration is crucial
                constructor(inputValue: AnyTypeNeeded);
            }
        }
    }
}

Phaser.Physics.Box2D = class {
    public value = 42;
    constructor(private inputValue: AnyTypeNeeded) {}
};

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

Creating dynamic and interactive web pages can be achieved by utilizing either $_POST or $_GET with Modal,

In the snippet below, you'll find the HTML code that pulls an array of 6 objects from a database and displays them in a Bootstrap row successfully. <div class="row products"> <?php while($product = mysqli_fetch_assoc($featured)) ...

Adding and removing controls on Google Maps in real-time

Recently, I encountered an issue with my custom search bar overlapping some controls on my map. Despite adjusting the z-index of these controls, they continued to stay on top. To work around this problem, I thought about hiding the controls during the sear ...

What are the best practices for utilizing AngularJS's $sanitize service?

Recently, I stumbled upon a tutorial discussing authentication in AngularJS. The tutorial showcased an AuthenticationService that was structured similarly to this: angular.module("auth").factory("AuthenticationService", function ($http, $sanitize) { ...

Create a unique Bitcoin address using a derivation scheme

Starting with a derivation scheme that begins with tpub... for the testnet, I am looking to generate bitcoin addresses from this scheme. I also need a method that will work for the mainnet. Is there a library available that can assist me with this task? ...

Switch out two for loops with the find or filter method in JavaScript

In my unique approach, I am showcasing a variety of product details lists based on availability in various shops. To achieve this, I have implemented the following method. for (let i = 0; i < this.prodList.length; i++) { let setContent = false; for ...

Opt for res.render() over res.send() when developing in Node.js

I recently developed an image uploader for ckeditor. After uploading a file, I need to send back an html file that includes the name of the image to the client. Check out the code snippet below: router.post('/upload', function (req, res, next) ...

Angular: Real-time monitoring of changes in the attribute value of a modal dialog and applying or removing a class to the element

I cannot seem to figure out a solution for the following issue: I have two sibling div elements. The second one contains a button that triggers a modal dialog with a dark overlay. However, in my case, the first div appears on top of the modal dialog due to ...

Utilizing Nested ControlGroups in Angular2 rc1: A Comprehensive Guide

Seeking assistance with understanding the functionality of a control group. Attempting to implement something similar to this: app.component.ts: import { Component, OnInit } from "@angular/core"; import { FORM_DIRECTIVES, FormBuilder, ControlGroup } from ...

Currently, I am developing a Vue.js chat application. I am facing a challenge when it comes to sending the entire input div along with the keyboard popping up on Android devices. How can I achieve this

I'm in the process of developing a chat application using vuejs that will be accessed through a webview on Android. I currently have an input-bx element for sending messages, but I need to find a way to ensure it remains visible when the Android keybo ...

The error encountered with react createRef was caused by a faulty implementation

Here is the revised question post completing the answer In this particular code snippet, I have encountered an issue where my file browser opens correctly upon submission, however, the updated state is not reflected when I click the final submit button. ...

Using Typescript in the browser with Babel and Webpack: Step-by-Step Guide

I've been exploring the use of Typescript in my browser with a specific architecture: Typescript in browser architecture However, I'm facing an issue with the import/export functionality when running this command: tsc && babel build-ts -d lib && ...

VueJS functions properly on Google Chrome, however it may encounter compatibility issues when using

I am currently working on a VueJs app resembling an auction, with the backend powered by Laravel. Everything runs smoothly when I test it on Chrome, but for some reason, Safari seems to be giving me trouble. The app consists of two main components: Deale ...

The form created using jQuery is not submitting correctly because the PHP $_FILES array is empty

Creating an HTML form dynamically in jQuery and submitting the form data via Ajax to 'add_sw.php' for processing is my current challenge. However, I have encountered an issue where the PHP script cannot access the PHP $_FILES variable as it turn ...

Creating a scale effect similar to iCloud.com in Angular.JS: A step-by-step guide

Have you checked out the new icloud.com site? There's a cool effect on there that I want to try and recreate for a project I'm working on. When you go to and log in, you'll notice a loading gif followed by the calendar app scaling out to t ...

What could be the reason for receiving a Firebase INVALID_DYNAMIC_LINK_DOMAIN error message?

I'm having trouble implementing email verification in my React website. Whenever I use the sendSignInLinkToEmail function, I encounter the following error: XHRPOSThttps://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=xxxxxxxxxxxxxxxxxxx [ ...

Execute function when button is clicked in ExpressJS

I am looking to execute a function on my node server when a button on my website is clicked: What I currently have: Index.html (I have not included the entire content for simplicity) <button id="tv">tv</button> Client.js (Client side) const ...

What is the best approach to establish multiple global prefixes in a NestJS project?

I am looking to define multiple Global Prefixes for my application such as: admin/products admin/users admin/... api/products api/search api/... shop/products shop/cart shop/... In the main.ts file, I can set a single global prefix using th ...

Implementing a pop-up notification at the center of the display for empty fields

I am currently working on a task that requires me to display a pop-up message at the top-middle of the screen stating "please fill in all fields before submitting". This custom box should be stylable using CSS. Although the solution seems simple, I am str ...

Discovering the specifics of an appointment within a shift event using FullCalendar

The title of the question may not accurately depict the scenario I am about to discuss. I'm currently working with FullCalendar and utilizing an open source library that allows me to add resources at the top. You can view the outcome of this on Js ...

Adding an item into a list with TypeScript is as simple as inserting it in the correct

I am working with a list and want to insert something between items. I found a way to do it using the reduce method in JavaScript: const arr = [1, 2, 3]; arr.reduce((all, cur) => [ ...(all instanceof Array ? all : [all]), 0, cur ]) During the fir ...