Home > Net >  typescript doesn't recognize the result of function
typescript doesn't recognize the result of function

Time:06-10

I have created a typescript util that return true if the parameter is a function and false if not, but when I use it to discriminate the way that I use a variable, typescript doesn't recognize the check.

util:

export function isFunction<T>(value: T | undefined): boolean {
return typeof value === 'function';
}

usage

isFunction(group) ? group(el) : group

CodePudding user response:

That's not quite how user-defined type guards work:

function isFunction(x: unknown): x is Function { // note the 'is'
  return typeof x === 'function';
}

const a = Math.round(Math.random()) ? () => 5 : null;
const b = isFunction(a) ? a() : null; // no error;

A rare actually valid use-case for the Function interface.

Playground

CodePudding user response:

What you want is this Type predicate. No need to use generics.

export function isFunction(value: unknown): value is ((...args: any[]) => any) {
    return typeof value === 'function';
}

Working demo

CodePudding user response:

function isFunction<T>(value: T | undefined): boolean {
    return typeof value === 'function';
}

let imFn = (val: string) => {
    console.log('i am a', val)
}

let imNotFn = 'not function';

function execute(anything: any){
    console.log(isFunction(anything))
    isFunction(anything) ? anything('function') : console.log(anything);
}

execute(imFn);
execute(imNotFn);

Playground

  • Related