Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 390
Philip Feldmann Avatar asked Sep 20 '19 11:09

Philip Feldmann


1 Answers

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

like image 61
ford04 Avatar answered Nov 13 '22 19:11

ford04