如何从字符串数组推断对象键的类型

时间:2019-09-20 11:44:26

标签: typescript typescript-typings

我具有以下功能:

    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;
    }

此函数将接收n个字符串,并返回一个对象,该对象完全包含这些字符串作为键,并且具有随机值。

因此infer("abc", "def")可能返回{"abc": "1337", "def":"1338"}

是否有任何方法可以推断返回类型以从此函数获得完整的类型安全性?该函数的代码保证了每个键都将出现在返回的对象中,并且每个值都将是一个字符串。

1 个答案:

答案 0 :(得分:4)

您可以这样声明:

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