0

Is it possible to use the Tuple spreading syntax in Typescript to remove these function overloads? The complication is that I need to remap the function args to new types.

type Type = TString | TNumber
type TString = { tag: 'string' }
type TNumber = { tag: 'number' }

interface Mapping {
  string: string
  number: number
}

type Remap<T extends Type> = Mapping[T['tag']];

// can I collapse these function overloads in to one?
function checkFn<R extends Type, A extends Type, B extends Type, C extends Type>(argTypes: [A, B, C], retType: R, fn: (arg0: Remap<A>, arg1: Remap<B>, arg2: Remap<C>) => Remap<R>): void;
function checkFn<R extends Type, A extends Type, B extends Type>(argTypes: [A, B], retType: R, fn: (arg0: Remap<A>, arg1: Remap<B>) => Remap<R>): void;
function checkFn<R extends Type, A extends Type>(argTypes: [A], retType: R, fn: (arg: Remap<A>) => Remap<R>): void;
function checkFn(argTypes: any[], retType: any, fn: any): void {}

const stringType: TString = { tag: 'string' }
const numberType: TNumber = { tag: 'number' }

checkFn([numberType, stringType, numberType], numberType, (arg0, arg1, arg2) => 42)

TS playground

1 Answer 1

1

Using Variadic Tuple Types (see the docs for a less descriptive version) the answer is "yes":

type Type = TString | TNumber
type TString = { tag: 'string' }
type TNumber = { tag: 'number' }

interface Mapping {
  string: string
  number: number
}

type Remap<T extends Type> = Mapping[T['tag']];

function checkFn<P extends Type[], R extends Type>(
  argTypes: [...P],
  retType: R,
  fn: (...args: { [K in keyof P]: Remap<P[K] & Type> }) => Remap<R>
): void {}


const stringType: TString = { tag: 'string' }
const numberType: TNumber = { tag: 'number' }

checkFn(
  [numberType, stringType, numberType],
  numberType,
  (arg0: number, arg1: string, arg2: number) => 42);
Sign up to request clarification or add additional context in comments.

1 Comment

This is a perfectly appropriate answer. The only thing that it gives the runtime error checkFn is not defined, so I suggest removing declare and writing {} after void

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.