📌Intro
If a function doesn’t return anything, what’s its return type in TypeScript? Many developers guess undefined
but 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 void
to say “ignore the return value.”
🚩 Case 2: Async Functions (No Return)
For async
functions, 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 undefined
means the function must explicitly return undefined
.
Example of correct undefined
return:
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 void
unless you specifically want to enforce return undefined
;.
Top comments (0)