Reputation: 2589
I have an array of functions inside an object. One returns an object and the other one returns string:
{
id: 'test-1',
children: [
function childOne() {
return {
id: 'child-1'
}
},
function childTwo() {
return 'text.'
}
]
}
Is there a way to detect type of a return value without executing functions?
Upvotes: 4
Views: 662
Reputation: 1075039
Not in JavaScript, no, because:
TypeScript adds a layer of static type checking to JavaScript, if this is something that you regularly find you need. But even then, that information is erased at runtime, so if you need this information at runtime, TypeScript won't help.
Instead, you'll need to include that as information in the array, for instance:
{
id: 'test-1',
children: [
{
returns: "object",
fn: function childOne() {
return {
id: 'child-1'
};
}
},
{
returns: "string",
fn: function childTwo() {
return 'text.';
}
}
]
}
Or, since functions are objects:
{
id: 'test-1',
children: [
addReturns("object", function childOne() {
return {
id: 'child-1'
}
}),
addReturns("string", function childTwo() {
return 'text.'
})
]
}
...where addReturns
is:
function addReturns(type, fn) {
fn.returns = type;
return fn;
}
Upvotes: 9