Doua Beri
Doua Beri

Reputation: 10949

javascript: determine functions return type

Is there a way in javascript to determine the return type(if any) of a function?

example:

function doSomething(){
   return true;
}

to returned type is boolean.

example 2:

function doSomething2(x){
    if(x=="a") return 1;//number
    else return "bad x"; //string
}

Upvotes: 11

Views: 39977

Answers (7)

Aral Roca
Aral Roca

Reputation: 5919

If you wish to analyze the return type of a function without executing it, you can use the ts-morph library. However, keep in mind that it is a 1mb library primarily used for parsing files, so its usefulness may vary depending on the specific project. An example of using ts-morph to determine the return type of a function is as follows:

import { Project } from "ts-morph";

function getReturnType(fn: Function): ts.Type {
  const project = new Project();
  const sourceFile = project.createSourceFile("s.ts", fn.toString());
  return sourceFile.getFunctions()[0].getReturnType().getText()
}

getReturnType(function test(){ return 'test' }) // string
getReturnType(async function test(){ return 'test' }) // Promise<string>

Please note that there is an issue with arrow functions not working correctly with this code. However, if you know the parameters of the function (for example, if it is a configuration function used in your library), you can wrap the arrow function in a regular function and it should work:

function getReturnType(fn: Function): ts.Type {
  const project = new Project();
  const functionString = `function(l, n){ return (${fn.toString()})(l, n)}`
  const sourceFile = project.createSourceFile("s.ts", functionString);
  return sourceFile.getFunctions()[0].getReturnType().getText()
}

Upvotes: 1

gdoron
gdoron

Reputation: 150283

Check what the type is:

    var x = typeof doSomething2('a');
    
    if (x == "string")
        alert("string")
    else if (x == "number")
        alert("number");
    else if (x == "undefined")
        alert('nothing returned');
    else if (x == "boolean")
        alert("boolean");
    else
        alert(x);

A simple shorthand would of course be, assuming "undefined" would be fine to return instead of "nothing returned":

alert(typeof doSomething2('a'))

Example use:

[undefined, 'stringyMeThingy', 42, true, null].forEach(x => console.log(typeof x))

Upvotes: 8

kennethreyt
kennethreyt

Reputation: 161

you can use it as a function to be return

const determineFunc = (param) => typeof param;

console.log("logs==>", determineFunc(true));

Upvotes: 2

abhinav kumar
abhinav kumar

Reputation: 1803

If the function is returning object and we apply typeof on the returned value, then we will get value as object which is generic type but we may not know what specific object it is, To get the specific object what i have tried is constructor.name which has given the specific object which is returned .Also we have the alternative like Object.prototype.toString.call(value)

For Example

const li = document.createElement('li');
console.log(typeof li);//object
console.log(li.constructor.name);//HTMLLIElement
console.log(Object.prototype.toString.call(li));//[object HTMLLIElement]

SO we can see object is just a generic type for all object. And HTMLLIElement is the specific object returned by the function mentioned.

Upvotes: 0

The Alpha
The Alpha

Reputation: 146219

    function dosomething()
    {
        return true;
    }
    var myfunc=dosomething();
    if(typeof myfunc=="boolean") alert('It is '+typeof myfunc);

You can use

if(typeof myfunc=="boolean") or if(typeof myfunc=="number") or if(typeof myfunc=="string") 

or

if(typeof myfunc=="object") or if(typeof myfunc=="undefined") to determine the type.

Upvotes: 2

BNL
BNL

Reputation: 7133

No, you are going to have to run the function and check the type of the resulting value.

Upvotes: 4

josh.trow
josh.trow

Reputation: 4901

This isn't Haskell - Javascript functions can return anything.

Upvotes: 5

Related Questions