Check If a Variable Is of Function Type

Check if a variable is of function type

Sure underscore's way is more efficient, but the best way to check, when efficiency isn't an issue, is written on underscore's page linked by @Paul Rosania.

Inspired by underscore, the final isFunction function is as follows:

function isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}

Note: This solution doesn't work for async functions, generators or proxied functions. Please see other answers for more up to date solutions.

How do I detect whether a Python variable is a function?

If this is for Python 2.x or for Python 3.2+, you can use callable(). It used to be deprecated, but is now undeprecated, so you can use it again. You can read the discussion here: http://bugs.python.org/issue10518. You can do this with:

callable(obj)

If this is for Python 3.x but before 3.2, check if the object has a __call__ attribute. You can do this with:

hasattr(obj, '__call__')

The oft-suggested types.FunctionTypes or inspect.isfunction approach (both do the exact same thing) comes with a number of caveats. It returns False for non-Python functions. Most builtin functions, for example, are implemented in C and not Python, so they return False:

>>> isinstance(open, types.FunctionType)
False
>>> callable(open)
True

so types.FunctionType might give you surprising results. The proper way to check properties of duck-typed objects is to ask them if they quack, not to see if they fit in a duck-sized container.

TypeScript - check if object's property is a function with given signature

It doesn't look like typeof type guards exist for function types. It seems to be by design; see microsoft/TypeScript#2072 (that issue is about instanceof type guards but I'm guessing it's similar reasoning).

However, TypeScript does have user-defined type guards, meaning you can write a function that narrows the type of its argument any way you like.


TypeScript's static type system is erased when the code is compiled to JavaScript. At runtime, there is no such thing as (conf: {}) => void that you can examine. If you want to write a runtime test to distinguish values of type (conf: {}) => void from values of other types, you will only be able to go so far.

You can test if typeof x === "function". But that just tells you it's a function. It doesn't indicate how many parameters the function takes and what their types are. You could also check if x.length === 1 to see if the function expects one argument, although there are caveats around Function.length involving rest parameters and default parameters. But now you're kind of stuck.

At runtime, any information about function parameter types will have been erased, if those functions even came from TypeScript code in the first place. At most you could "probe" the function by calling it with some test parameters and checking to see if things break. But that's a destructive test with possible side effects, and defeats the purpose of checking a function is the right type before calling it.


Maybe you are fine with this limitation and will just assume that a function whose length is 1 is a good enough test. Or maybe you have some other test (e.g., maybe you can add a property named isOfRightType whose value is true to all such functions you care about, and then just test for that property. This eliminates false positives by introducing the possibility of false negatives). Once you know your runtime test, you can make a type guard:

function isFunctionOfRightType(x: any): x is (conf: {})=>void {
return (typeof x === 'function') && (x.length === 1); // or whatever test
}

// ... later

let property: this[keyof this] = utils.getProperty(this, name);
if (isFunctionOfRightType(property)) { property(conf); } // no error now

Playground link to code

Haxe: How to check if a variable is a function

You're looking for Reflect.isFunction().

Check if a variable is of async function type

This seems like a bad idea. There are plenty of functions out there that are effectively async (returning a Promise) but not flagged as such (perhaps they are transpiled down for browser support).

If you truly wanted to test if a function was async, it might be better to test if the return value has a .then property:

const maybeTask = f()
if ('then' in maybeTask) {
maybeTask.then( .... )
}

Typescript: how to pass variable with complex type to a function without redefining type

If the users array is avaiable in the scope of the function, you could use the typeof operator.

function handleUser(user: typeof users[number]){

}

You can index the typeof users with number to get the type of an array element inside users.

how to tell if a javascript variable is a function

Use the typeof operator:

if (typeof model[property] == 'function') ...

Also, note that you should be sure that the properties you are iterating are part of this object, and not inherited as a public property on the prototype of some other object up the inheritance chain:

for (var property in model){
if (!model.hasOwnProperty(property)) continue;
...
}


Related Topics



Leave a reply



Submit