[英]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.