繁体   English   中英

TypeScript:对于这个 function,如何将类型显式传递给 generics

[英]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. 这是代码

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'])

所以在这里我定义了两个类型参数TK ,它们是由 TS 编译器推断出来的,因为当我调用 function 时,我没有显式地传入类型。

现在我的问题是,如果我想明确地将类型传递给 function,我应该如何重写 function? 我想这样做是因为我很好奇类型推断在这里是如何工作的

所以这是我的尝试

getValues<typeof obj, string[] extends keyof typeof obj>(obj, ['a'])

但是编译器并不高兴。 存在解析错误Parsing error: '?' expected Parsing error: '?' expected

假设您真的想显式传递一个类型,我认为在 function 的调用中不允许使用extends

getValues<typeof obj, keyof typeof obj>(obj, ['a'])

暂无
暂无

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

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