Tips for changing window.function in Typescript

I'm attempting to log when a method is automatically called. (I found the code snippet on )

augment(withFn) {
        let name, fn;
        for (name in window) {
            fn = window[name];
            if (typeof fn === 'function') {               
                window[name] = (function(n, f) {   // An error is occurring here.
                    const args = arguments;
                    return function() {
                        withFn.apply(this, args);
                        return fn.apply(this, arguments);
                    };
                })(name, fn);
            }
        }
    }

and then call this.

this.augment(function(name, fn) {
        console.log('calling ' + name);
    });

An error is being thrown:

ERROR in src/app/app.component.ts(81,17): error TS2740: Type '() => any' is missing the following properties from type 'Window': Blob, TextDecoder, TextEncoder, URL, and 232 more.

I'm wondering how I can override a window function?

Answer №1

When working with TypeScript, the window[name] property is treated as a member of the Window interface which should include objects like Blob, TextDecoder, and TextEncoder.

This behavior is due to the fact that the Window interface contains a dynamic property definition:

interface Window extends EventTarget, WindowTimers, ... {
  ...
  [index: number]: Window;
}

which allows for referencing window objects in frames such as window[0], window[1], and so on.

To address this issue, you can extend the existing Window interface to handle your scenario:

declare global {
  interface Window {
    [index: string]: () => any; // or simply 'any'
  }
}

Additionally, ensure that the variable let name is explicitly declared as type string:

let name: string

Below is the complete code snippet:

app.component.ts

export class AppComponent {
  ...

  ngOnInit() {
    this.augment(function(name, fn) {
        console.log('calling ' + name);
    });
  }

  augment(withFn) {
    let name: string, fn;
    for (name in window) {
      fn = window[name];
      if (typeof fn === 'function') {
        window[name] = (function (n, f) {
          const args = arguments;
          return function () {
            withFn.apply(this, args);
            return fn.apply(this, arguments);
          };
        })(name, fn);
      }
    }
  }
}

declare global {
  interface Window {
    [index: string]: () => any;
  }
}

Note: There are simpler ways to resolve TypeScript errors:

Ignore an error:

// @ts-ignore
window[name] = (function(n, f) {

Use the any keyword:

(window[name] as any) = (function(n, f) {

or

(<any>window[name]) = (function (n, f) {

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

Typescript: Establishing a class method with parameters that are inherent to the class

After creating a class, I realized that there is repeated logic that can be extracted into a method on the class to be reused by other properties of the class. class Card { protected readonly data: Data; protected readonly user: User; nameVal: strin ...

Can you explain the distinction between `any[]` and `{ [s: string]: any }`?

I was attempting to make this code snippet function properly: test(a: any[]) { let b: string[][] = []; b.push(Object.keys(a[0])); b.push(...a.map(e => Object.values(e))); } However, the compiler is throwing an error for the b.push(...a.ma ...

Angular - Dividing Functionality into Multiple Modules

I am currently working with two separate modules that have completely different designs. To integrate these modules, I decided to create a new module called "accounts". However, when I include the line import { AppComponent as Account_AppComponent} from &a ...

What is the method for displaying script commands within package.json files?

With a multitude of repositories, each one unique in its setup, I find myself constantly referencing the package.json file to double-check the scripts. "scripts": { "start": "npm run dev" "build:dev": "N ...

Structural directive fails to trigger event emission to parent component

Following up on the question posed here: Emit event from Directive to Parent element: Angular2 It appears that when a structural directive emits an event, the parent component does not receive it. @Directive({ selector: '[appWidget]' }) export ...

Replace current element in Angular 2

I am looking to change the current element during routing instead of simply adding to it. Below is the code I am currently using: <router-outlet> <div class="=row" style="height:30%"></div> <div class="=row"> <a ...

Encountering an issue with PrimeNG's <p-calendar> component: the error message "date

I encountered an issue resulting in the following error message: core.es5.js:1020 ERROR Error: Uncaught (in promise): TypeError: date.getMonth is not a function TypeError: date.getMonth is not a function This error occurs whenever I attempt to implement ...

How can conditional types be implemented with React Select?

I am working on enhancing a wrapper for React-select by adding the capability to select multiple options My onChange prop is defined as: onChange: ( newValue: SingleValue<Option>, actionMeta: ActionMeta<Option>, ) => void Howev ...

Placing gaps after every group of four digits

I am currently working with Ionic 4 and Angular 8, attempting to insert a space every 4 digits entered by the user. However, the function I have written seems to be malfunctioning, as it inserts a space after each action the user takes following 4 numbers. ...

What is the best method to convert a union type to an array and vice versa, in order to obtain all potential values?

For instance: type Y = 'c' | 'd'; const yVals = ??? Y; // ['c', 'd'] Alternatively, you can derive a union type from an array of all possible values. The objective is to ensure each potential value is included onl ...

Angular 2: A guide to connecting Input with model property using getter and setter functions

I'm currently developing an Angular 2 web application. The model I have created consists of a few primary properties, along with other properties that are calculated based on those primary values. For each property in my model, I have implemented get ...

Tips on how to incorporate a .js file into my .tsx file

I ran into an issue with webpack displaying the following message: ERROR in ./app/app.tsx (4,25): error TS2307: Cannot find module './sample-data'. The imports in my code are as follows: import * as React from 'react'; import * ...

When attempting to create a generic key value interface, Typescript will throw an error if a mapped type is used that declares properties or methods

I am attempting to design an interface that can accept generic key-value pairs in the following format export interface GetModel<K extends string, T> { [key in K]: T; } However, I encountered this error message A mapped type may not declare prop ...

Discovering the origins of the node.js native modules and delving into the intricacies of typed modules

I am using a Windows machine and trying to locate where node fetches the source code for native modules. On my system, I can only find the @types file which contains "Typed Only" modules. For example, the module "assert" is available in the master/lib fold ...

Pause for Progress - Angular 6

I'm looking for a solution to solve the following issue. I need to access a property that will store data from an http request. Therefore, I want to verify this property only after the transaction is completed. validateAuthorization(path: string): ...

The lite-server is not compatible for initiating the Angular2 Quickstart

Struggling to get the Angular2 Quick start app up and running on my Windows system. Unfortunately, I've hit a roadblock with the "lite-server". Despite installing dependencies (npm install), when attempting to run the app (npm start), an error pops u ...

Spread an all-encompassing category across a collection

What is the method in TypeScript to "spread" a generic type across a union? type Box<T> = { content: T }; type Boxes<string | number> = Box<string> | Box<number>; (Given that we are aware of when to use Boxes versus Box) ...

experiencing an excessive amount of re-renders after transferring data to a distinct component

At the moment, I have implemented this logic to display data based on the results of a graphql query, and it is working well: const contacts = () => { const { loading, error, data } = useUsersQuery({ variables: { where: { id: 1 }, ...

Utilizing Conditional Aurelia Validation Based on Element's Display Status

Currently, I am in the process of setting up a license subscription form using Aurelia and the Aurelia Validation plugin. Within this form, there is a fieldset dedicated to personal information which contains mostly required fields that are validated by Au ...

`Why isn't GetServerSideProps being triggered for a nested page in Next.js when using Typescript?

I have been working on a page located at /article/[id] where I am trying to fetch an article based on the id using getServerSideProps. However, it seems that getServerSideProps is not being called at all as none of my console logs are appearing. Upon navi ...