Home > Enterprise >  No constituent of type 'true | CallableFunction' is callable
No constituent of type 'true | CallableFunction' is callable

Time:01-12

The full error:

This expression is not callable.
  No constituent of type 'true | CallableFunction' is callable

This is the code that was triggering the error:

public static base(
    text,
    callB: boolean | CallableFunction = false,
    
  ) {
    const sw = Swal.fire({
      text,
      });

    if (callB) {
      sw.then(callB());
    }
  }

I changed the type of callB to :

 callB: (param: any) => void |boolean = false

and when I remove the callB type definition:

callB= false

I get this error:

This expression is not callable.
  Type 'Boolean' has no call signatures

CodePudding user response:

This is what you are looking for:

function base(text: string, callB: false | CallableFunction = false) {
  console.log(text);
  if (callB) {
    callB();
  }
}

Essentially, you want to pass a function or false. When it is truthy you want to call the function.

But as per your definition

function base(text: string, callB: boolean | CallableFunction = false) {
  console.log(text);
  if (callB) {
    callB();
  }
}

this would be a valid call base('some str', true) where callB is true and not a function that it will try to execute using callB(). Not boolean is not callable, it is? Hence the error.

TS Playground link: https://tsplay.dev/m056qW

CodePudding user response:

The type

boolean | Function

is equivalent to

true | false | Function

Now because a value of type Function is truthy, your check

if (callB)

narrows the type of callB to

true | Function

and true is not callable, hence the error.

It's not clear how your base method is meant to be used so I've outlined two solutions:

If true isn't a valid input, adjust your parameter type accordingly

static base(
    text, 
    callB: false | CallableFunction = false
) {
    if (callB) {
        callB();
    }
}

If true is a case you must handle, use a more precise conditional check such as

if (typeof callB === 'function') {
    callB() // OK
}
  •  Tags:  
  • Related