📌Intro
If a function doesn’t return anything, what’s its return type in TypeScript? Many developers guess undefinedbut the real answer is a bit more nuanced. Let’s break it down with examples.
🚩 Case 1: Normal Functions (No Return)
When you don’t return anything from a normal function, TypeScript infers its return type as void.
function logMessage(message: string): void {
console.log(message);
}
Even if you don’t annotate it, TypeScript will automatically infer it:
function logMessage(message: string) {
console.log(message);
}
// inferred as: (message: string) => void
At runtime, this function technically returns undefined, but TypeScript uses voidto say “ignore the return value.”
🚩 Case 2: Async Functions (No Return)
For asyncfunctions, it’s just Promise<void>.
async function logMessage(message: string): Promise<void> {
console.log(message);
}
Or with arrow functions:
const logMessage = async (message: string): Promise<void> => {
console.log(message);
};
Even if you don’t write the annotation, TypeScript infers Promise<void>.
🤔 Why Not undefined?
It’s tempting to write:
function logMessage(message: string): undefined {
console.log(message);
}
But this will error:
Function lacks ending return statement and return type does not include 'undefined'
That’s because undefinedmeans the function must explicitly return undefined.
Example of correct undefinedreturn:
function doNothing(): undefined {
return undefined; // ✅ works
}
But in most cases, what you want is void, not undefined.
🏗 Real-Life Example
A logger utility:
function logger(message: string): void {
console.log(`[LOG]: ${message}`);
}
async function saveAndLog(data: string): Promise<void> {
// simulate saving
await new Promise(res => setTimeout(res, 1000));
logger(`Saved data: ${data}`);
}
Here:
- logger returns nothing →
void - saveAndLog is async →
Promise<void>
💡 Extras
-
void= “I don’t care about the return value.” -
undefined= “This function must return undefined explicitly.”
👉 Always prefer voidunless you specifically want to enforce return undefined;.
Top comments (0)