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

Phi*_*ann 6 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;
    }
Run Code Online (Sandbox Code Playgroud)

这个函数将接受 n 个字符串并返回一个包含这些字符串作为键的对象,并带有随机值。

所以infer("abc", "def")可能会回来{"abc": "1337", "def":"1338"}

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

for*_*d04 5

你可以这样声明:

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>
Run Code Online (Sandbox Code Playgroud)

操场