Home > Mobile >  How can I assign a value to a variable of a callable type?
How can I assign a value to a variable of a callable type?

Time:05-15

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?

CodePudding user response:

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' });

CodePudding user response:

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'))

  • Related