4

Given the following:

interface Foo {
  attr: string;
  (a: string): number;
  (a: number): number;
}

How one would create a type that only select the function overloads, meaning:

interface Bar {
  (a: string): number;
  (a: number): number;
}

I found solution when there is just one call signature, my situation is when there are more than one call signatures.

Thanks

1

1 Answer 1

7

There is no perfect way to do this. There is no support to just remove the properties and the version that extracts function signatures has limitations. We can get get a version with multiple overloads to work:

interface Foo {
  attr: string;
  (a: string): number;
  (a: number): number;
}

type JustSignatures<T> =
  T extends { (...args: infer A1): infer R1; (...args: infer A2): infer R2; (...args: infer A3): infer R3; (...args: infer A4): infer R4 } ?
  {
    (...args: A1): R1; (...args: A2): R2; (...args: A3): R3; (...args: A4): R4
  } :
  T extends { (...args: infer A1): infer R1; (...args: infer A2): infer R2; (...args: infer A3): infer R3 } ?
  {
    (...args: A1): R1; (...args: A2): R2; (...args: A3): R3
  } :
  T extends { (...args: infer A1): infer R1; (...args: infer A2): infer R2 } ?
  {
    (...args: A1): R1; (...args: A2): R2
  } :
  T extends { (...args: infer A1): infer R1; } ?
  {
    (...args: A1): R1;
  } :
  never;


type FooSignatures = JustSignatures<Foo>
// type FooSignatures = {
//     (a: string): number;
//     (a: number): number;
// }

Playground Link

This will still have the limitation of not working for functions with generic type parameters. Also I seem to remember a bug in the compiler that cause the above approach to have issues in some corner cases, but it should for the most part work.

Sign up to request clarification or add additional context in comments.

1 Comment

It does work though I can even begin to understand what's going on here. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.