Wang Liang
Wang Liang

Reputation: 4434

Typescript: what means value is (...args: any[]) => any

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

Why value is (...args: any[]) => any is used instead of boolean ?

Upvotes: 0

Views: 542

Answers (1)

xdumaine
xdumaine

Reputation: 10329

This is called a Type Guard which gives typescript additional type information than a runtime boolean check would. https://medium.com/swlh/typescript-generics-and-type-guards-explained-by-example-177b4a654ef6

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

export function isFunctionBool(value: any): boolean {
  return typeof value === 'function';
}

const doSomething = (fn: any) => {
    // using a runtime type check
    if (isFunctionBool(fn)) {
        fn(1, 2, 3);
    //  ^^ typescript still thinks the type is `any`
    }

    // using a typeguard
    if (isFunctionTypeGuard(fn)) {
        fn(1, 2, 3);
    //  ^^ typescript now knows the type is `(...args: any[]) => any` 
    }    
}

Upvotes: 1

Related Questions