Is there a way to duplicate the method signature and apply it to a different method?

I came across a library that contains the following class:

class Dog {
  public run(speed: number, movement: number): void;
  public run(speed: number, type: string): void;
  public run(speed: number, opts: string | number): void {
    // performing some actions here
  }
}

My aim is to develop another interface with a different method name but matching the exact signature of Dog.run. I attempted the following approach, however, it failed as I couldn't reference the run method within Dog by using Dog.run:

interface SpecialDog {
   runWithSpecialPower: (...args: Parameters<Dog.run>) => ReturnType<Dog.run>
}

In this scenario, I cannot simply extend SpecialDog from Dog because I prefer the method name to be runWithSpecialPower rather than just run. Is there any way for me to duplicate the method signature of another method?

TS Playground

Answer №1

If you're in this situation, it's likely that you are searching for indexed access types. Suppose you have an object called foo with a type of Foo and a key named "bar", then the type of foo.bar would be Foo["bar"], using the bracket notation. (Dot notation can't be used to look up property types due to conflicts with namespace/module exports, refer to microsoft/TypeScript#30815.) In your specific case, you need Dog["run"]:

interface SpecialDog {
  runWithSpecialPower: Dog["run"];
}

Let's test it out to confirm:

declare const specialDog: SpecialDog;
specialDog.runWithSpecialPower(1, 2);
specialDog.runWithSpecialPower(1, "okay");

Everything seems to be working fine.

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

Suggestions for efficiently filtering nested objects with multiple levels in RXJS within an Angular environment?

Just a Quick Query: Excuse me, I am new to Typescipt & RxJS. I have this JSON data: [ { "ID": "", "UEN": "", "Name": "", "Address": "", "Telephone&quo ...

Using `useState` within a `while` loop can result in

I'm working on creating a Blackjack game using React. In the game, a bot starts with 2 cards. When the user stands and the bot's card value is less than 17, it should draw an additional card. However, this leads to an infinite loop in my code: ...

Integrate Angular 2 into the current layout of Express framework

After generating an express structure with express-generator, I ended up with the standard setup: bin bld node_modules public routes views app.js package.json Now, I want to enhance the views and routes directories by organizing them as follows: v ...

Adjust the Express JS response to prevent certain specific values from being included

I am currently working on an Express application that is returning large decimal numbers as text in the responses. The issue arises when the numbers are either 'Infinity' or 'NaN'. I am looking for a way to replace these values with emp ...

tips for utilizing a variable for inferring an object in typescript

In my current code, I have the following working implementation: type ParamType = { a: string, b: string } | { c: string } if ('a' in params) { doSomethingA(params) } else { doSomethingC(params) } The functions doSomethingA and doSomething ...

Arrange the items that are missing from Array B to be located at the bottom of Array A, organized in a file tree structure

I have two arrays containing different types of objects. Each object in the arrays has a title assigned to it. My goal is to compare these two arrays based on their titles and move any files that are not included in the bottom part of the fileStructure arr ...

Creating a realistic typewriter effect by incorporating Code Block as the input

I am looking to add a special touch to my website by showcasing a code segment with the Typewriter effect. I want this code block not only displayed but also "typed" out when the page loads. Unfortunately, I have been unable to find a suitable solution s ...

Nestjs opts to handle invalid routes by throwing a NotFoundException rather than a MethodNotAllowed

I've recently developed a Rest API using NestJS and now I'm focusing on customizing error responses. Specifically, I want to address the scenario where a user calls an endpoint with the incorrect HTTP method. Take for instance the endpoint GET / ...

What is the best way to associate a select dropdown with a form in Angular 2 using formBuilder

After conducting some research, I was surprised to find that the process is not as straightforward as I had expected. I have come across various methods using ngModel, such as Bind and fetch dropdown list value in typescript and Angular2, among others. Ho ...

Define the format for the output file name in TypeScript

I am trying to change the filename of a TypeScript generated js file. How can I accomplish this? For instance, I currently have MyCompany.ClassA.ts The default output filename is MyCompany.ClassA.js However, I would like the output filename to be MyComp ...

Child component in Angular2 makes an observer call to its parent object

Let me try to explain this in the best way possible. I have a service that includes an observable class responsible for updating itself. This observable class needs to be pushed out to the app using the observer within the service. How can I trigger that ...

What is the reason behind the ability to assign any single parameter function to the type `(val: never) => void` in TypeScript?

Take a look at the code snippet below interface Fn { (val: never): void } const fn1: Fn = () => {} const fn2: Fn = (val: number) => {} const fn3: Fn = (val: { canBeAnyThing: string }) => {} Despite the lack of errors, I find it puzzling. For ...

Exploring Nested JSON Iteration in Angular4

I am struggling to iterate through a nested JSON and extract the desired output. Can someone assist me in retrieving the bpmn:startEvent id value from the JSON provided below? { "bpmn:definitions":{ "@attributes":{ "xmlns:xsi":"h ...

Is it possible to prevent casting to any by improving type definitions?

My query can be best elucidated with the following code snippet. The comments within the code aim to provide clarity on the nature of the question. type MediaFormats = "video" | "audio"; type IMediaContent<TType extends MediaFormats, TValue> = { ...

Display all values of an array in a single array using Angular

I have an array with values that are structured as shown in the image https://i.sstatic.net/SIo0N.png I am trying to consolidate them into a single array like { "1vwxnrjq", "dasdada", "adsdadsada"} console.log(items); this.ids = items.id; console.log(th ...

Sending a specific object and its corresponding key as parameters to a reusable component in Angular: T[K]

I am currently working on developing a generic component in Angular and Typescript version 4.4.4. The goal is to create a component where I can set both an object (obj) and specific keys (properties). Here's a simplified version of my text component: ...

Avoiding the use of destructuring for undefined values in JavaScript can be achieved by implementing

Upon receiving the response registryReportSettings from the server: this.getRegistrySettings(registry.Id).subscribe((registryReportSettings: { extended: ReportPropertiesRequest }) => { const { objectProperties, reportProperties, textProperties } = reg ...

Top picks for ReactJS Typescript accounts

As a novice programmer, I am working on learning ReactJS/NodeJS/Typescript through project-based practice. Currently, I am developing a social media platform and have encountered an issue. I want to display different random users from my MySQL database in ...

Why is TypeScript resorting to using 'any' for specific prop type definitions in React?

Having some trouble with my props typing: export interface ITouchable { isDisabled?: boolean; margin?: Margin; height?: number; bgColor?: string; } The definition of Margin is as follows: type Margin = | { top?: number; bottom?: nu ...

Typescript enhances React Native's Pressable component with a pressed property

I'm currently diving into the world of typescript with React, and I've encountered an issue where I can't utilize the pressed prop from Pressable in a React Native app while using typescript. To work around this, I am leveraging styled comp ...