Reputation: 15660
I'm using a library that has this 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 {
// perform some stuff
}
}
I want to create another interface with a different method name but with the same method signature as Dog.run
. I have tried this but it doesn't work because I cannot refer to the run
method in Dog
by using Dog.run
:
interface SpecialDog {
runWithSpecialPower: (...args: Parameters<Dog.run>) => ReturnType<Dog.run>
}
In this case, I can't extend SpecialDog
from Dog
too because I want the method name to be runWithSpecialPower
instead of just run
. Is there a way I can copy the method signature of another method?
Upvotes: 2
Views: 733
Reputation: 329868
In this case you're probably just looking for indexed access types. If you have an object foo
of type Foo
with a key named "bar"
, then the type of foo.bar
is Foo["bar"]
, using the bracket notation. (You can't look up property types with dot notation, as it conflicts with namespace/module exports, see microsoft/TypeScript#30815.) In your case, you want Dog["run"]
:
interface SpecialDog {
runWithSpecialPower: Dog["run"];
}
And let's verify that it works:
declare const specialDog: SpecialDog;
specialDog.runWithSpecialPower(1, 2);
specialDog.runWithSpecialPower(1, "okay");
Looks good.
Upvotes: 2