0
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 ?

1 Answer 1

1

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` } } 
Sign up to request clarification or add additional context in comments.

7 Comments

value is (...args: any[]) => any is not returnning type of isFunction ?
@MERN no, that's saying "this function is asserting that the argument is a value with a type of (...args: any[]) => any"
But, generally, after :, we declared the function's return types in typescript
Except with : variable is Type syntax
@MarcelToth function Foo(arg1: any): arg1 is T { ... } the arg1 is T clause indicates that the return type is boolean, and also asserts that arg1 either is or is not of type T.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.