AI Hints
TypeScript · Lesson 14 of 120

Return Types

Say what comes back.

⏱ 2 min read▶ Video at 11:54🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

A function can also say what it returns. Write a colon and the type after the brackets. Then TypeScript checks every return statement inside.

Return Types
From the video: Return Types
  • Say what comes back
  • After the brackets
  • Every return checked

A forgotten case

Label must return a string. But we forgot to return anything when the order is small. Run it. TypeScript notices the function might return undefined.

app.tstypescript
function label(total: number): string {
  if (total >= 50) {
    return "Free delivery";
  }
}
Output
app.ts line 1: Function lacks ending return statement and return type does not include 'undefined'.

Fixed

We add the missing return. Run it. Both cases return a string.

app.tstypescript
function label(total: number): string {
  if (total >= 50) {
    return "Free delivery";
  }
  return "Delivery £4.99";
}

console.log(label(65), "|", label(20));
Output
Free delivery | Delivery £4.99

Summary

Write return types on functions, so every path is checked. Next, optional and default parameters.

Key takeaways
  • ): string
  • Every path
  • Missing returns caught
Next up: Optional and Default Parameters — flexible calls