【发布时间】:2018-04-28 19:00:15
【问题描述】:
我正在实现一个call 函数,该函数接收对象和属性名称,然后在传递的属性处调用驻留在传递对象中的函数。
function call<
T,
K extends {
[K in keyof T]: T[K] extends Function ? K : never
}[keyof T],
>(t: T, func: K) {
t[func]();
}
看起来 ts 对此很满意并正确过滤了属性(没有prop,只有do 可用):
但它也在我调用函数的行上显示错误:t[func]();:
Cannot invoke an expression whose type lacks a call signature.
Type '{}' has no compatible call signatures.
我发现了类似的issue [Type deduction using mapped types and generics],但是它作为另一个issue [Call signatures of union types] 的副本被关闭了。显然问题是第二个泛型参数实际上是满足条件的所有属性名称的联合类型。
除了转换为any之外,还有其他方法可以解决这个问题吗?
PS:Playground
【问题讨论】:
标签: typescript