简体   繁体   English

Typescript:使用泛型类型的键作为函数的参数 object 键

[英]Typescript: Use generic type's keys as function's argument object keys

I have a function where the generic type T (which is the fuction's return type) is a dictionary with keys of type string and values of type unknown (because they can be anything).我有一个 function,其中通用类型T (这是函数的返回类型)是一个字典,其中的键类型为string ,值类型为unknown (因为它们可以是任何东西)。 I would like for the single argument that this function takes to be an object whose keys must match those of the generic type T .我想要一个参数,即这个 function 是一个 object ,它的键必须与通用类型T的键匹配。 This is, essentially, a function that maps an object's key/val pairs to a different set of values after some transformation work.这本质上是一个 function,它在一些转换工作之后将对象的键/值对映射到一组不同的值。

I'd like to use the following (note the index type in the function argument)我想使用以下内容(注意 function 参数中的索引类型)

export function convert<T extends Record<string, unknown>, S extends keyof any>(items: {
  [key: keyof typeof T]: string
}): T {
  //...do stuff
  return someObj as T;
}

The important thing here is keyof typeof T .这里重要的是keyof typeof T This doesn't work as I get an error:这不起作用,因为我收到错误:

TS2693: 'T' only refers to a type, but is being used as a value here.

I'm not sure how to remedy this, or why T is considered a value here.我不确定如何解决这个问题,或者为什么T在这里被视为一个值。 Does anyone know what I'm doing wrong?有谁知道我做错了什么? The various utility types and index types that I'm using don't seem to resolve my issue.我使用的各种实用程序类型和索引类型似乎无法解决我的问题。 I'd like callers of the function to get warned when they try to pass objects that don't have all keys that match the type once it is defined in the implementation.我希望 function 的调用者在尝试传递不具有与实现中定义的类型匹配的所有键的对象时收到警告。

Thanks谢谢

You have the syntax a bit wrong, a mapped type is what you want not an index signature:您的语法有点错误,映射类型是您想要的而不是索引签名:

export function convert<T extends Record<string, unknown>>(items: {
  [key in keyof T]: string
}): T {
  //...do stuff
  return items as T;
}

Playground Link 游乐场链接

You could also use the Record type instead of a custom mapped type:您还可以使用Record类型而不是自定义映射类型:

export function convert<T extends Record<string, unknown>>(items: Record<keyof T, string>): T {
  //...do stuff
  return items as T;
}

Playground Link 游乐场链接

You could also map the other way around if you need to capture more info from the items .如果您需要从items中获取更多信息,您也可以反过来拨打 map。 Also I find this was more easy to understand, but the displayed type is not expanded by default:我还发现这更容易理解,但默认情况下不会扩展显示的类型:

export function convert<T extends Record<string, string>>(items: T): Record<keyof T, unknown> {
  //...do stuff
  return items;
}

Playground Link 游乐场链接

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

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