简体   繁体   English

如何从字符串数组中推断 object 键的类型

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

I have the following function:我有以下 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.这个 function 将接受 n 个字符串并返回一个 object 包含这些字符串作为键,具有随机值。

So infer("abc", "def") might return {"abc": "1337", "def":"1338"} .所以infer("abc", "def")可能会返回{"abc": "1337", "def":"1338"}

Is there any way to infer the return type to get complete type-safety from this function?有没有办法从这个 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. function 的代码保证每个键都将出现在返回的 object 中,并且每个值都是一个字符串。

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 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM