Augmenting Object Scope in Typescript

I have a requirement to enhance the Object methods by adding a new method called "isEmpty".

// typings/object.d.ts

declare global {
    interface Object {
        isEmpty(): boolean;
    }
}

Object.prototype.isEmpty = function (this: Object) {
    for (let key in this) {
        if (this.hasOwnProperty(key)) {
            return false;
        }
    }

    return true;
};

After defining the custom method, I want to utilize it in my code like so:

let myEmptyDict = {};
let myFullDict = {"key": "value"};

console.log(myEmptyDict.isEmpty()); // true
console.log(myFullDict.isEmpty()); // false

However, I'm encountering an issue where isEmpty is not recognized. How can I troubleshoot and resolve this problem? I am currently working with Typescript version 3.6.2.

Answer №1

Your knowledge is mostly correct, but here are some additional resources for further details: GitHub issue and this Stack Overflow answer.

export {}; // ensure this is a module

declare global {
  interface Object {
    isEmpty(): boolean;
  }
}

Object.prototype.isEmpty = function(this: Object) {
  for (let key in this) {
    if (this.hasOwnProperty(key)) {
      return false;
    }
  }

  return true;
};

let myEmptyDict = {};
let myFullDict = { key: "value" };

console.log(myEmptyDict.isEmpty()); // true
console.log(myFullDict.isEmpty()); // false

TypeScript Playground

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

Sorting functionality is functional, but the table content remains unsorted within the Angular Material Table

There seems to be a strange issue with the sorting arrows on the table surface. Even though the sorting functionality should be working, it's not sorting the table as expected... Here is the HTML : <div class="mat-elevation-z8"> <table ma ...

In my experience with typescript and express, I have encountered challenges getting res.send to work properly with explicit types in my controller. However, I have found that it does work seamlessly when the type

Currently working on setting up a project with express and typescript in an MVC layout. The index.ts file is responsible for routing and directing the request and response objects to the appropriate controller function, such as the GetRoot function in the ...

Utilizing v-for in Vue with TypeScript to generate multiple checkboxes

My goal was to capture the values of checkboxes and store them in an array using v-model. However, I encountered an issue where the first time I toggle a checkbox, it doesn't register. Only after checking a second box and hitting submit does the secon ...

Ways to implement type checking for vuex commit using TypeScript

In the Vuex store, I have an action tree structured like this export const actions: SalaryActionTree<SalaryState, RootState> = { async setSalaryOperationUnpaidListByUserId( {commit}, {user_id, pageNum}) { try { let res ...

Destructuring is not supported in useParams when using TypeScript

During my exploration of this video entitled "JWTUser Sessions with ReactJS & GraphQL...", I encountered a part at this timestamp where the presenter destructures the useParams() method from the react-router-dom library. However, when I tried to implement ...

TypeScript: implementing function overloading in an interface by extending another interface

I'm currently developing a Capacitor plugin and I'm in the process of defining possible event listeners for it. Previously, all the possible event listeners were included in one large interface within the same file: export interface Plugin { ...

Ways to include various inputs with chip

I am currently working on a project that involves implementing an email field using the chip component. However, I have encountered an issue where pasting multiple email values for the first time inserts them into the field successfully. But when I try to ...

Receiving a Promise<fullfield> as a result

I have a situation where I am adding several promises to an array: const apiCallsToMake = []; apiCallsToMake.push(this.getDataFromUnsplash(copyInputParams)); apiCallsToMake.push(this.getDataFromPexels(copyInputParams)); apiCallsToMake.pu ...

Vue 3 is unable to detect any alterations made to an object that was created externally to the Vue component

I am working with a class called Character in a file named Character.ts /// This is called when server responds public setAttributeByType(type: StatsTypes, value: number): void { switch (type) { case StatsTypes.STRENGTH: ...

Access an Angular 2 component through an email hyperlink including querystring parameters

I need to create a deep link with query string parameters for a component, so that when the link is clicked, it opens up the component in the browser. For example: exmaple.com/MyComponent?Id=10 I want to include a link in an email that will open the com ...

Substitute terms with the usage of array map

Here is an array for you (2) ['beginning=beginner', 'leaves=leave'] as well as a string its beginner in the sounds leave that has been converted to an array using the following code var words = text.split(' '); My goal ...

Mapping an array based on its individual values

How can I sum values in an array of objects based on a specific condition? [{amount:100, prefix:'a'},{amount:50, prefix:'b'},{amount:70, prefix:'a'},{amount:100, prefix:'b'}] Is there a method to map and calculate t ...

How can I specify UTC timezone in Angular Material datepicker?

Currently, I have a datepicker set with a timezone of +3 hours using the following configuration: @Component({ selector: 'date-picker', templateUrl: './date-picker.component.html', styleUrls: ['./date-picker.component.scss&a ...

When using Vue to bind a data URI to the img src property, I noticed that the image in the browser only updates when there is

Currently, I am working on generating a base64 string to represent an image and passing that image data to a child component as part of an object property. The object class I am using for this purpose has an image property along with some other properties ...

What is the most effective way to transform values into different values using TypeScript?

If I have a list of country codes and I want to display the corresponding country names in my component, how can I achieve this using props? interface MyComponentProps { countryCode: 'en' | 'de' | 'fr'; } const MyComponent: ...

Tips on optimizing data processing for quicker display with ngFor

I am currently facing an issue with loading a JSON file containing 3500 data. The data appears very slowly on the view, causing the application to work sluggishly. Below is a snippet of the JSON: export class Service { private items = new Arr ...

Ways to access file attributes and transfer a file in ionic 4?

I am facing an issue while attempting to transfer a file from my mobile device to Google bucket using Ionic 4. Although I can successfully upload the file, I am struggling to extract its properties from the file object. Below is the method I am using: as ...

Tips for creating a unit test case for a specialized validator in angular reactive forms

Looking for guidance on creating a test case for this specific method: export class CustomErrorStateMatcher implements ErrorStatematcher { isErrorState(control: FormControl,form:NgForm | FormGroupDirective | null){ return control && control.inval ...

I'm encountering an error while trying to build my Ag-Grid using npm run build, can someone help me figure out

Being relatively new to Next.js and web development in general, my background mainly consists of working with compiled languages. I recently embarked on a project to build a web app using Ag-Grid, drawing inspiration from an example I found on a public Git ...

Guide to mocking the 'git-simple' branchLocal function using jest.mock

Utilizing the simple-git package, I have implemented the following function: import simpleGit from 'simple-git'; /** * The function returns the ticket Id if present in the branch name * @returns ticket Id */ export const getTicketIdFromBranch ...