Philip Feldmann
Philip Feldmann

Reputation: 8435

How to infer the type of object keys from a string array

I have the following function:

    const infer = (...params: string[]): Record<string, string> => {
      const obj: Record<string, string> = {};
      // Put all params as keys with a random value to obj
      // [...]
      return obj;
    }

This function will take n strings and return an object containing exactly those strings as keys, with random values.

So infer("abc", "def") might return {"abc": "1337", "def":"1338"}.

Is there any way to infer the return type to get complete type-safety from this function? The code of the function guarantees that each key will be present in the returned object and that each value will be a string.

Upvotes: 6

Views: 700

Answers (1)

ford04
ford04

Reputation: 74730

You could declare it like this:

const infer = <T extends string[]>(...params: T): Record<T[number], string> => {
  const obj: Record<string, string> = {};
  // Put all params as keys with a random value to obj
  // [...]
  return obj;
};

const t = infer("a", "b", "c") // const t: Record<"a" | "b" | "c", string>

Playground

Upvotes: 5

Related Questions