1

How do I map an array parameter to another parameter type.

An example of what I want is below:


enum Item {
   A = 'A',
   B = 'B',
   C = 'C'
}
type ItemType = `${Item}`

type MappingFn = ( dependencies ) => string;

const createConfig = (dependencies: ItemType[], mappingFn: MappingFn) => {
 //
}

createConfig([ Item.A, Item.B ], (dependencies) => {
 // dependencies should be typed as Record<A | B, any>
  // ie I can access 'dependencies.A' or 'dependencies.B' but error with 'dependencies.C'
} );

1 Answer 1

1

Your createConfig() function should be generic in the type K corresponding to the literal types of the elements of the dependencies parameter, constrained to ItemType if you want:

const createConfig = <K extends ItemType>(
  dependencies: K[],
  mappingFn: (dependencies: Record<K, any>) => string
) => {
  //
}

Let's see it in action:

createConfig(['A', 'B'], (dependencies) => {
  dependencies.A; // okay, any
  dependencies.B; // okay, any
  dependencies.C; // error, property C not known to exist
  return "wantsAString"
});

Looks good.

Playground link to code

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

4 Comments

Yeah this is similar to what I did. However, I have issue that it allows all keys not just the ones specified. I've updated my example as it's not 'string'.
Okay, updated. Hopefully the question stabilizes soon.
Thanks. It's weird I can see your example works as expected, but my actual implementation doesn't. Although it is a bit more complicated as I have another generic passed in the function. So then when I call the function K is expected to be defined.
That's a different issue, see this SO question/answer.

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.