TypeScript Callable Instance | Cododel
CODODELDEV
EN / RU
Back to Deck
[utility]

TypeScript Callable Instance

SOURCE TypeScript
VERSION 1.0
AUTHOR Cododel

A TypeScript utility that transforms a class instance into a callable function using Proxy. Allows you to invoke an instance as a function while maintaining access to all its properties and methods.

Use Case

Perfect for creating fluent APIs where you want an object to be both callable and maintain its class interface:

class Calculator {
value: number = 0
call(x: number) {
this.value += x
return this
}
reset() {
this.value = 0
return this
}
}
const calc = toCallable(new Calculator())
calc(5)(10) // Callable via call() method
console.log(calc.value) // Access properties: 15
calc.reset() // Call methods

Features

  • Type-safe: Full TypeScript support with proper type inference
  • Dual interface: Use as function or access class members
  • Zero overhead: Minimal runtime cost via Proxy
  • Clean API: Transparent delegation to call() method

How it works

  1. Creates a Proxy around a bound function
  2. apply trap delegates to instance’s call() method
  3. get trap provides access to instance properties/methods
  4. Types preserved via TypeScript generics

Source Code

toCallable.ts

type hasCallMethod = { call: (...args: any[]) => any }
export default function toCallable<T extends hasCallMethod>(instance: T) {
type argsType = Parameters<T['call']>
const fn = (...args: argsType) => {
return instance.call(...args)
}
return new Proxy(fn.bind(instance), {
apply: (target, _thisArg, argsList: argsType) => target(...argsList),
get: (target, prop) => {
// Delegate to the class instance if the property exists there
if (prop in instance) {
return instance[prop as keyof T]
}
// Otherwise, look for it on the function
return target[prop as keyof typeof target]
},
})
}
[ ▲ 0 ]