Home > Back-end >  How to infer sum type of values picked from property from passed array of objects
How to infer sum type of values picked from property from passed array of objects

Time:10-13

I am trying to pass array of objects to a function. This function has to look at all types of values behind one of the properties of its objects. These types of values should be passed as type parameter to a returned function

What types have to be filled as question marks to achieve these results?

type A = { key: 'a' };
type B = { key: 'b' };
type C = { key: 'c' };

type Xs = (A | B | C)[];

const fn1 = (arg1: ???) => {
  return {
    f2: (arg2: ???) => null,
  };
};

// should fail
fn1([]).f2('a');
// should also fail
fn1([{ key: 'a' }]).f2('c');
// correct
fn1([{ key: 'a' }, { key: 'b' }]).f2('a');

Something like Pick<ValuesType<(A | B | C)[]>, 'key'>['key'] could be used to get "a" | "b" | "c" type. But how to infer the subset of types forming the passed array remains puzzle to me.

CodePudding user response:

Try this:

const fn1 = <K extends string>(arg1: {key: K}[]) => {
  return {
    f2: (arg2: K) => null,
  };
};

Playground Link

If you must restrict the original argument to only be of type Xs or a subtype, then try this:

const fn1 = <T extends Xs>(arg1: T) => {
  return {
    f2: (arg2: T[number]['key']) => null,
  };
};

Playground Link

  • Related