Fix - A function whose declared type is neither void nor any

avatar

Borislav Hadzhiev

Tue Mar 01 20222 min read

banner

Photo by Lê Tân

Fix - A function whose declared type is neither void nor any #

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.

index.ts
// ⛔️ 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.

If you don't return a value from a function, the function implicitly returns undefined.

To solve the error, return a value that matches the return type of the function.

index.ts
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.

index.ts
// 👇️ 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.

index.ts
// ⛔️ 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.

This is often a source of confusion when using callback functions - returning a value from a nested function doesn't mean that you return the value for the outer function.

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.

index.ts
// ✅ 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).

Use the search field on my Home Page to filter through my more than 1,000 articles.