Typescript: remove all `Function.prototype` methods

1.2k views Asked by At

Is it possible to create this type: callable object (function) BUT without Function.prototype methods?

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

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

I tried something like this with no success:

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."

So maybe also the question should sound like "how do I add call signatures to the type"

1

There are 1 answers

3
Willem van der Veen On

You could do the following:

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

Object.setPrototypeOf(myFunc, null);

// myFunc still works
myFunc();

console.log(Object.getPrototypeOf(myFunc))

Here we use Object.setPrototype() to set the prototype of the function object explicitly to null.