是否可以创建这种类型:可调用的对象(函数)但没有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."
所以也许这个问题听起来也像是“如何向该类型添加呼叫签名”
答案 0 :(得分:0)
您可以执行以下操作:
function myFunc () {
console.log('test');
}
Object.setPrototypeOf(myFunc, null);
// myFunc still works
myFunc();
console.log(Object.getPrototypeOf(myFunc))
在这里,我们使用Object.setPrototype()
将功能对象的原型显式设置为null
。