Incorporating a new method into the Object prototype to provide universal access across all modules

I've been delving into Typescript experimentation and I'm attempting to enhance the Object prototype by adding a property that can be accessed by all objects within my modules.

Here's what I've developed so far:

In a Common.ts file

Object.defineProperty(Object.prototype, 'notNull', {
    value: function(name: string){
        if(this === null || this === undefined){
            throw new Error(`${name} cannot be null nor undefined`);
        }

        return this;
    },
    enumerable: false
});

Now, I want to implement it in another file like this:

module SomeModule{
    class Engine{
        constructor(public horsePower: number, public engineType: string){}
    }

    class Car{
        private _engine: Engine;

        constructor(private engine: Engine){
            //Compiler error arises here due to the absence of notNull
            this._engine = engine.notNull('engine');
        }
    }
}

I'm currently unsure about exporting "Object" with module.exports in Common.ts as it doesn't seem to serve any purpose when imported into other files. Is there a more effective way to achieve this?

Thank you.

Answer №1

When making changes to the Object.prototype, it will impact all aspects within the environment where your code is executing. This is why experts usually caution against extending native objects.

However, if you decide to proceed down this route, here's what you should do:
After altering the prototype, the new functionality will be available during runtime, but the compiler may not recognize this modification and could raise errors when attempting to utilize the updated method.

To resolve this issue, you can employ global augmentation:

declare global {
    interface Object {
        notNull(name: string): this;  
    }
}

Edit

A commenter on this answer suggested that this technique works only with modules (import/export). If you are not using modules, then follow these steps:

interface Object {
    notNull(name: string): this;  
}

Place this snippet in a file that is included in all your TypeScript source files, perhaps a .d.ts file.


2nd Edit

If you are using modules, simply use the following approach:

export class Engine{
    constructor(public horsePower: number, public engineType: string){}
}

export class Car {
    private _engine: Engine;

    constructor(private engine: Engine){
        //Compiler will flag an error about missing notNull 
        this._engine = engine.notNull('engine');
    }
}

No need to wrap it with module SomeModule { ... }

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

Using Angular and Typescript to implement mathematical formulas involving date object subtraction

I need help converting the following Excel formula to Typescript. I keep running into an error that says 'The left-hand and right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type'. Can anyon ...

Having difficulty resolving sub-modules using webpack

Currently, I am trying to set up the @microsoft/signalr npm package with webpack by importing the module using import * as signalR from '@microsoft/signalr'. However, I encountered an error message indicating that webpack is unable to resolve the ...

The TypeError thrown by Mongo .updateMany() indicates that the property 'updateMany' of the object is not a valid function

Currently, I have a collection named users, which contains the following documents: Document 1: { "_id": { "$oid": "5934fd84d6ba4c241259bed1" }, "first_name": "Joe", "last_name": "Smith", "username": "jsmith", "email": "&l ...

Guide to sending both JSON data and form data in a single request using Laravel 9

I am working on a form where I need to input multiple images that will be converted into JSON format. The HTML for my form: create.blade.php <form method="post" action="{{ route('m_announcement.store') }}" enctype="mu ...

Is there a way to identify legitimate contacts and phone numbers within an Android application using Javascript or Typescript?

I am developing an Android app where I need to show a list of contacts and specify if they are part of the app's network. However, my goal is to only display valid contacts while excluding unwanted ones such as toll-free numbers or data balance check ...

checkbox revision

I'm attempting to update some text indicating whether or not a checkbox is checked. The issue is that when the checkbox is checked, the textbox disappears and the text takes its place. <form name="myForm" id="myForm"> <input type="checkb ...

"Unfortunately, this container did not send out any hits" - Google Tag Manager

After successfully integrating Google Tag Manager into my Next.js website, here is the implemented code: import '../styles/global.css'; import type { AppProps } from 'next/app'; import Script from 'next/script'; import NextNP ...

Using TypeScript with async await operators, promises, and the memoization pattern

I am currently in the process of updating my code to incorporate the latest TypeScript enhancements. We have implemented various memoization patterns, with the main goal being to ensure that services with multiple subscribers wait for one call and do not t ...

Break apart the string and transform each element in the array into a number or string using a more specific type inference

I am currently working on a function that has the ability to split a string using a specified separator and then convert the values in the resulting array to either strings or numbers based on the value of the convertTo property. Even when I call this fun ...

Ideas and Recommendations for Building a Laravel and Vue.js Hybrid Structure for MPA/SPA Applications

Consider the innovative approach I've been pondering - a combination of MPA and SPA, where each page functions as a Single Page Application, yet still reloads when navigating from one page to another (e.g. index.blade.php to posts.blade.php) like a tr ...

Guide on attaching an event to every dynamically created element in JavaScript

I'm currently generating 'li' elements dynamically using a loop and running into issues when it comes to assigning events to each generated element. My goal is to assign an onclick event to every li element that is created. Check out the co ...

The jQuery window.on event is not functioning when trying to handle the same hash change

How to fix jQuery window.on hashchange issue when clicking on the same hash? See the code snippet below for a potential solution: function addMargin() { let header = $('.header__wrapper').outerHeight(); let headerHeight = $('body& ...

Styling div elements to match the dimensions of table rows in CSS

When it comes to CSS, I wouldn't call myself an expert; My question is: is there a way for a div tag to inherit dimensions from specific table rows based on their class or id? For instance: Imagine we have a table with multiple rows, but we don&apos ...

Utilizing Snowpack to implement private class methods in JavaScript

In my front-end development, I utilize private JavaScript class methods and Snowpack for my workflow. Unfortunately, I've encountered an issue with Snowpack (as of v2.15.0-pre.5) not supporting private class methods. When trying to build using snowpa ...

I'm curious as to why window.opener is null in a popup when utilizing Google OAuth, and what is the most effective way to transfer the access token to the parent window

In my React application, I am working with Google OAuth and implementing it through a popup. The setup involves using Passport with my own custom backend. I start by supplying the initial URL to the popup window, which is the entry point on my backend that ...

Tips for successfully transferring values from an onclick event in JavaScript to a jQuery function

I am encountering a challenge with an image that has an onclick function associated with it. <img id='1213' src='img/heart.png' onclick='heart(this.id)'> This particular function needs to be triggered : function heart ...

Surprising discovery of the reserved term 'await'

function retrieveUsers() { setTimeout(() => { displayLoadingMessage(); const response = fetch("https://reqres.in/api/users?page=1"); let userData = (await response.json()).data; storeAllUserDa ...

Vuetify's v-badge showcasing an exceptionally large number in style

Encountering an issue with using v-badge and v-tab when dealing with large numbers in a v-badge. Managed to find a CSS workaround by setting width: auto; for adjusting the size of v-badge to accommodate huge numbers, but now facing an overlap with my v-ta ...

Unable to pass Ajax value to Laravel controller

Currently, I am facing an issue while trying to retrieve a value from an ajax request in my controller. Although my JavaScript function successfully displays the desired value in an alert, when I attempt to pass this value as data to the controller, it is ...

Encountering this error message while attempting to synchronize an Ionic Angular project in Xcode using npx cap sync

Every time I try to run npx cap sync on my Ionic Angular project in Xcode, I encounter the following error. [!] The plist file at path `/Users/user/Documents/GitHub/project-name/ios/App/App.xcodeproj/project.pbxproj` doesn't exist. I face the ...