我有一个简单的功能。您知道JS中的函数是对象吗?所以我还添加了一些属性。有两个重要的细节:
Function.prototype
方法(call
,apply
等)在IntelliSense(IDE自动完成)弹出窗口中显示,所以我使用内置的Exclude
类型删除Function.prototype
方法。所以我的代码如下所示,并且无法按预期运行:
type ExcludeFunctionPrototypeMethods<T extends () => any> = {
[K in Exclude<keyof T, keyof Function>]: T[K]
}
function someFunc<T extends () => any>(t: T): ExcludeFunctionPrototypeMethods<T> {
return {} as any
}
someFunc(() => {})() // the methods are excluded, but when calling,
it fails with "Cannot invoke an expression whose type lacks a call
signature. Type 'ExcludeFunctionPrototypeMethods<() => void>'
has no compatible call signatures."
那么如何避免最后一条错误消息?如何在映射类型中添加呼叫签名?请注意,下面的代码将修复错误,但还会添加Function.prototype
方法,这是不希望的:
type ExcludeFunctionPrototypeMethods = {...} & {
(): any // <- the call signature added, but methods of Function.prototype added as well
}