Home > Blockchain >  How can i have callable tuple property?
How can i have callable tuple property?

Time:05-08

I have the following function

function test(cb: Function | number) {
  let item = { height: 0}
  if(typeof cb === 'number') {
    item.height = cb;
  }
  if(typeof cb === 'object') {
    item.height = cb();
  }
}

so i am passing dynamic property - it will be either a number or Function i am checking if it is a number then initialise directly if it is a function then i am calling the function which i send as a callback and it will return a number

function getNumber() {
   return 2;
}

test(getNumber);

i keep getting the error when i try item.height = cb();

 No constituent of type 'number | Function' is callable.

How can i solve ? I don't want to use any here - if i use any the error will be gobe but it is not a nice solution.

CodePudding user response:

I don't get this error in ts playground, but try to change typeof cb === 'object' to cb instanceof Function and Function | number to () => number | number.

CodePudding user response:

The following works for me:

function test(cb: Function | number) {
  let item = { height: 0}
  if(typeof cb === 'number') {
    item.height = cb;
  }
  if(typeof cb === 'function') {
    item.height = cb();
  }
}

function getNumber() {
   return 2;
}

test(getNumber);

Check if cb is a function, not an object. This way TypeScript understands that cb in that case is callable.

  • Related