Borislav Hadzhiev
Tue Mar 01 2022·2 min read
Photo by Lê Tân
The "A function whose declared type is neither void nor any must return a value" error occurs when we have explicitly set the return type of a function, but the function does not return a value. To solve the error, make sure to return a value from the function or remove the return type.
Here is an example of how the error occurs.
// ⛔️ Error: A function whose declared type is // neither 'void' nor 'any' must return a value.ts(2355) const getPromise = (): Promise<number> => { Promise.resolve(42); };
We've set the return type of the getPromise
function to be Promise<number>
,
but we don't return a value from the function.
undefined
.To solve the error, return a value that matches the return type of the function.
const getPromise = (): Promise<number> => { return Promise.resolve(42); };
If your function doesn't need to return anything, you can simply remove the function's return type.
// 👇️ const getPromise: () => void const getPromise = () => { Promise.resolve(42); };
Now the function has a return type of void, which represents the return type of functions that don't return a value.
Sometimes you might get this error when you have a complex function with nested conditions and callbacks.
// ⛔️ Error: A function whose declared type is // neither 'void' nor 'any' must return a value.ts(2355) const getNumber = (): number => { function inner() { if (Math.random()) { return 100; } return 200; } inner(); };
The function above gets the same error, because we've set the function's return
type to be number
, but the function doesn't return a value.
The inner
function returns a value, but getNumber
does not.
The inner()
function in the example returns a number, but if you want to
return the number
from the outer function's return value, you have to
explicitly do it.
// ✅ OK now const getNumber = (): number => { function inner() { if (Math.random()) { return 100; } return 200; } return inner(); };
Now we explicitly return the return value of the inner
function.
We had to do this, because you only return a value for the function in whose
scope you've used the return
statement (or the implicit arrow function
return).