What is the correct way to type "this" to ensure it works properly when called in a subclass method?

Let's consider including an extension method to the existing Object:

declare global {
  interface Object {
    ext<B>(f: (x: this) => B): B;
  }
}

The aim is to apply it as shown below:

"x".ext(x => x.toUpperCase())
//or
(1).ext(x => x + 1)

However, this won't work, as the function's x parameter is assumed to be Object.

I expect it to be assumed as "this" (String/Number in these scenarios), the type of .ext()'s receiver.

Answer №1

Just a friendly reminder: extending native prototypes like Object.prototype is generally considered bad practice. It can lead to unexpected behavior and conflicts with other code. It's recommended to use a separate function with the object passed as a parameter instead. Disclaimer over!


If you want the compiler to handle this, consider using generics and adding a this parameter to the method. By doing so, the compiler can infer the types for you:

declare global {
  interface Object {
    ext<B, T>(this: T, f: (x: T) => B): B;
  }
}

With this setup, you can use:

"x".ext(x => x.toUpperCase()); // it works
(1).ext(x => x + 1) // it works too

This might not cover all scenarios, but it has been successful in the cases I've tested. Hope this information proves useful. Good luck!

Playground link to code

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

Is there a type-safe alternative to the setTimeout function that I can use?

When running my tests, I encountered an issue with the setTimeout method making them run slower than desired. I initially attempted to address this by using "any" in my code... but that led to complaints from eslint and others. Now, I have implemented a ...

Signing in to a Discord.js account from a React application with Typescript

import React from 'react'; import User from './components/User'; import Discord, { Message } from 'discord.js' import background from './images/background.png'; import './App.css'; const App = () => { ...

Is it possible that using npm link could be the root cause of the "module not

As I delve into understanding how to utilize TypeScript modules in plain JavaScript projects, it appears that I am facing a limitation when it comes to using npm linked modules. Specifically, I can successfully use a module that is npm-linked, such as &apo ...

"Exploring the power of index signatures and methods in Typescript

What might be the reason for code producing a ts(2411) error? class Greeter { [key: string]: string | number[]; greeting: string; constructor(message: string) { this.greeting = message; } greet(): string { return "Hel ...

Removing a key from an index signature in Typescript - a step-by-step guide

In my web application built with Angular, we encountered a need for a data type to store translations of strings in different languages. To address this requirement, a team member defined the following type: export class TranslatedString { [language: str ...

The module imported by Webpack appears to be nothing more than a blank

I am attempting to integrate the "virtual-select-plugin" library into my Typescript project using webpack. Unfortunately, this library does not have any type definitions. Upon installation via npm, I encountered the following error in the browser: TypeErro ...

Ensure that Angular resolver holds off until all images are loaded

Is there a way to make the resolver wait for images from the API before displaying the page in Angular? Currently, it displays the page first and then attempts to retrieve the post images. @Injectable() export class DataResolverService implements Resolv ...

Exploring the synergies between Angular 5 and atmosphere.js

I've been trying to incorporate atmosphere.js into my angular 5 project. So far, I've followed these steps: npm install --save @types/atmosphere.js npm install --save atmosphere.js In addition, I have set up a service as shown below: import { ...

Automatically shift focus to the next input when reaching the maximum length in Angular

Looking for a smoother way to focus the next input element in Angular without manually specifying which one. Here's my current HTML setup... <div class="mb-2 digit-insert d-flex align-items-center"> <div class="confirmation-group d-flex"&g ...

Powering up your React components with MDX, Storybook, and Typescript!

Currently, I am attempting to incorporate MDX markup into the creation of live documentation for my storybook. However, upon running the storybook, an error is occurring: Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: C ...

Connecting a hybrid/web client application to established remote web services outlined through a set of WSDL specifications

Summarizing the Problem I am faced with the task of integrating a mobile hybrid application, likely built on Ionic, that will need to indirectly consume several SOAP web services. My goal is for the TypeScript client in the mobile app to have knowledge of ...

What is the best way to establish the primary color for the entire app?

Is there a way to easily set the color for @react-native-material/core's theme? I managed to change the color but I don't want to have to do it individually for each component. ...

Tips for integrating and utilizing the MSAL (Microsoft Authentication Library for JavaScript) effectively in a TypeScript-based React single page application

Issue I'm encountering difficulties importing the MSAL library into my TypeScript code. I am using the MSAL for JS library with typings in a basic TypeScript/React project created using create-react-app with react-typescript scripts. As someone who i ...

Unable to resolve TypeScript error: Potential 'undefined' object

Here is the code snippet that I am working with: const queryInput = useRef() const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault() if (queryInput && queryInput.current) { console.log(`queryInput.cur ...

Issue with ngModelChange and change events not functioning properly in Internet Explorer 11

Within a text input field, I have implemented single-way binding in addition to utilizing a number formatter pipe. I have also set up an (ngModelChange) event handler to remove any commas that are added by the number formatter, and a (change) event to tri ...

The Typescript error occurs when trying to assign a 'string' type to a 'SetStateAction<null>'

For my project, I am delving into creating a global context using TypeScript. As a newcomer to TypeScript, I found a helpful guide in this blog post (). Despite following the outlined steps, I keep encountering an error message saying "Type 'string&ap ...

Different combinations of fields in Typescript types

Take a look at this defined type: type MyType = | { a: number } | { b: number } | { c: number } | ({ b: number } & { c: number }); The goal is to prevent the combination of 'a' with either 'b' or 'c'. const o1: ...

Issue: Interface not properly implemented by the service

I have created an interface for my angular service implementation. One of the methods in the service returns an observable array, and I am trying to define that signature in the interface. Here's what I have so far: import {Observable} from 'rxj ...

How to retrieve static attributes while declaring an interface

class A { public static readonly TYPE = "A"; } interface forA { for: A.TYPE } I am facing an issue while trying to access A.TYPE from the forA interface in order to perform type guarding. The error I encounter is: TS2702: 'A' only refe ...

Creating a .d.ts file for a JavaScript file that exports a plain object - tips and best practices

I am attempting to include a .d.ts file for an existing js file. The type.js file looks like this: // type.js export default { NORMAL: '001', CHECK: '002', }; Now, I have added a type.d.ts file as follows: // type.d.ts decla ...