[英]TypeScript: How can I explicitly pass in the type to the generics for this function
I am learning TypeScript and I was trying to use mapped types to write a function that only allows users to extract values off of the object when the keys indeed exist on the object. I am learning TypeScript and I was trying to use mapped types to write a function that only allows users to extract values off of the object when the keys indeed exist on the object. Here is the code
这是代码
const obj = {
a: 1,
b: 2,
c: 3
}
function getValues<T, K extends keyof T>(obj: T, keys: K[]) {
return keys.map(key => obj[key])
}
getValues(obj, ['a', 'b'])
So here I defined two type parameters T
and K
and they are inferred by the TS compiler because when I called the function I didn't explicitly pass in the types.所以在这里我定义了两个类型参数
T
和K
,它们是由 TS 编译器推断出来的,因为当我调用 function 时,我没有显式地传入类型。
Now my question is, what if I want to explictly pass the types into the function, how should I rewrite the function?现在我的问题是,如果我想明确地将类型传递给 function,我应该如何重写 function? I want to do this because I am curious about how the type inference works here
我想这样做是因为我很好奇类型推断在这里是如何工作的
so this is my attempt所以这是我的尝试
getValues<typeof obj, string[] extends keyof typeof obj>(obj, ['a'])
However the compiler is not happy.但是编译器并不高兴。 There is an parsing error
Parsing error: '?' expected
存在解析错误
Parsing error: '?' expected
Parsing error: '?' expected
Assuming you really want to pass a type in explicitly, I don't think using extends
is allowed in the invocation of the function.假设您真的想显式传递一个类型,我认为在 function 的调用中不允许使用
extends
。
getValues<typeof obj, keyof typeof obj>(obj, ['a'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.