0

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
1
  • 1
    By does not recognize you mean isFunction is not caught by compiler ? Commented Jun 9, 2022 at 10:56

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I tried Function but it felt too weird to use lol
@thurasw I hear you, think that's only the second time I've ever used it. First time was something like interface SpecialFunction extends Function { (x: number) => string; [someSymbol]: "I am special"; } because I needed the extra property typed.
2

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

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.