Last updated: Feb 27, 2024
Reading time·2 min
The "A function whose declared type is neither void nor any must return a value" error occurs when we explicitly set the return type of a function but the function doesn't 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 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 error occurs because we
set the function's return type to
be number
but the function doesn't return a value.
The inner
function returns a value, however, getNumber
does not.
The inner()
function in the example returns a number but if you want to return
the number
from the outer function, use an
explicit return statement.
// ✅ 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).
You can learn more about the related topics by checking out the following tutorials: