简体   繁体   English

函数签名中通用类型的类型

[英]Type of generic type in function signature

I am trying to write a generic function where I would like to have an argument of a type of other generic parameter. 我正在尝试编写一个通用函数,希望在该函数中具有其他通用参数类型的参数。 Here is a code sample: 这是一个代码示例:

function find<K,V,P extends keyof V>(map: Map<K,V>, property: P, value: number): boolean {
  for (const entry of Array.from(map.values())) {
    if (entry[property] == value)
      return true;
  }
  return false;
}

let map = new Map<string, string>([["a", "test"]]);
const result: boolean = find<string,string,'length'>(map, 'length', 4); //is the entry 'a' of length 4 ?

This doesn't work since the type of value: number is hard-coded. 由于value: number的类型value: number是硬编码的,所以这不起作用。 I would like to be it the type of property:P in the V type. 我想成为V类型的property:P的类型。 Is this even possible? 这有可能吗?

使用映射类型

function find<K,V,P extends keyof V>(map: Map<K,V>, property: P, value: V[P])

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

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