Home > Net >  types for a function that can change the values of a nested Record
types for a function that can change the values of a nested Record

Time:01-13

How to derive return types from generic function arguments?

With the following solution, P will be of type number ( because of the first argument ), and because of this, {value: 'myString'} will be marked as a wrong type.

type MyGenericWrapper<T> = {value: T;}

// get all values out of the generic object wrappers
function allValues<P>(...args: MyGenericWrapper<P>[]) : P[] {
  return args.map(arg => arg.value);
}

const [a, b] = allValues({value: 1}, {value: 'myString'});

How can i tell the compiler that P should be derived for every function argument?

So that a will be of type number and b of type string

CodePudding user response:

You can have the generic parameter store the type of the entire array, and then use a mapped type in the return type:

function allValues<P extends MyGenericWrapper<any>[]>(...args: P): { [K in keyof P]: P[K]["value"] };
function allValues(...args: MyGenericWrapper<any>[]) {
  return args.map(arg => arg.value);
}

I'm using an overload here to keep the desired signature separate of the implementation (otherwise, you get annoying errors that require annoying fixes).

Playground

  • Related