Typescript:如何在映射类型中添加呼叫签名?

时间:2018-10-05 18:06:23

标签: typescript mapped-types

我有一个简单的功能。您知道JS中的函数是对象吗?所以我还添加了一些属性。有两个重要的细节:

  • 我不希望Function.prototype方法(callapply等)在IntelliSense(IDE自动完成)弹出窗口中显示,所以我使用内置的Exclude类型删除Function.prototype方法。
  • 我动态地添加方法,因此我必须对函数使用Mapped Type。

所以我的代码如下所示,并且无法按预期运行:

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
}

0 个答案:

没有答案