0

How can I assign a variable of a callable type (type with call signature)?


interface CallableType<T> {
  (isSomething: boolean): T
  description: string
}

const fn: CallableType<number> = ?

const result = fn(false) 

How can I assign a value to fn so that it can have a property description and it's callable at the same time?

mod7ex
  • 874
  • 9
  • 27

2 Answers2

2

A shorter solution would be to use Object.assign:

// fn is (<T>(x: T) => T) & { description: string }
const fn = Object.assign(<T>(x: T) => x, { description: 'description here' });
kelsny
  • 23,009
  • 3
  • 19
  • 48
0

I found this way but maybe not the best

interface CallableType<T> {
  (x: T): T
  description: string
}

let foo = <T>(x: T) => x

const fn = foo as CallableType<string>

fn.description = 'description here'

console.log(fn('some string'))

mod7ex
  • 874
  • 9
  • 27
  • 2
    No need to youse type assertion `as CallableType`. TypeScript track mutation here. Please see [example](https://tsplay.dev/w2anVW) and related [question](https://stackoverflow.com/questions/68643123/why-does-typescript-track-mutation-of-function-static-properties) – captain-yossarian from Ukraine May 14 '22 at 13:45