AI Hints
TypeScript · Lesson 13 of 120

Functions

Typed parameters.

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

Functions are where types help the most. Each parameter gets a type. Then every call is checked, so nobody can pass the wrong thing.

Functions
From the video: Functions
  • Typed parameters
  • Every call checked
  • No wrong arguments

A typed function

Delivery cost takes an order total, which must be a number. Orders of fifty pounds or more get free delivery. Run it. Two calls, two answers.

app.tstypescript
function deliveryCost(total: number) {
  return total >= 50 ? 0 : 4.99;
}

console.log(deliveryCost(65));
console.log(deliveryCost(20));
Output
0
4.99

A wrong argument

Now we pass the total as text. Run it. The call is rejected, at the exact argument.

app.tstypescript
function deliveryCost(total: number) {
  return total >= 50 ? 0 : 4.99;
}

deliveryCost("65");
Output
app.ts line 5: Argument of type 'string' is not assignable to parameter of type 'number'.

Summary

Give every parameter a type, and every call is checked. Next, return types.

Key takeaways
  • (total: number)
  • Calls checked
  • Errors at the argument
Next up: Return Types — say what comes back