打字稿:删除所有“ Function.prototype”方法

时间:2018-10-05 17:34:58

标签: typescript types function.prototype

是否可以创建这种类型:可调用的对象(函数)但没有Function.prototype方法?

let callableObject = () => 'foo'
callableObject.bar = 'baz'

callableObject() // 'foo'
callableObject // {bar: 'baz'}
callableObject.call // error

我尝试了类似的尝试,但没有成功:

type ExcludeFunctionPrototypeMethods<T extends () => any> = {
    [K in Exclude<keyof T, keyof Function>]: T[K]
}

function f<T extends () => any>(t: T): 
ExcludeFunctionPrototypeMethods<T> {
    return {} as any
}

f(() => {})() // 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."

所以也许这个问题听起来也像是“如何向该类型添加呼叫签名”

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

function myFunc () {
  console.log('test');
}

Object.setPrototypeOf(myFunc, null);

// myFunc still works
myFunc();

console.log(Object.getPrototypeOf(myFunc))

在这里,我们使用Object.setPrototype()将功能对象的原型显式设置为null