Bugs
TypeScript Async Function Types: How to Type Promises Correctly
Incorrectly typed async functions can hide that a function returns a Promise, causing callers to forget to await and get unexpected results.
❌ Incorrectly Typed Async
async function getUser(id: string) { // Inferred as Promise<User | null>
return await db.findUser(id);
}
// Caller forgets await:
const user = getUser('123'); // Promise object, not User!
if (user) { // Always truthy — Promise is always truthy
console.log(user.name); // undefined
}✅ Explicit Return Type
async function getUser(id: string): Promise<User | null> {
return await db.findUser(id);
}
const user = await getUser('123'); // User | null
if (user) {
console.log(user.name); // Type-safe
}💡
Pro tip: Enable @typescript-eslint/no-floating-promises. It flags every Promise-returning call that isn't awaited or explicitly handled.
Paste this code into LearnCodeGuide
Detect TypeScript vulnerabilities and bugs automatically with AI-powered analysis.
Analyze TypeScript Code →