Functions & Casting

Functions & Casting: A TypeScript function is like the terms of a will — 'I'm giving you these two things (parameters), and in return you must give me back something of this kind

A TypeScript function is like the terms of a will — 'I'm giving you these two things (parameters), and in return you must give me back something of this kind (the return type)'; if the promise isn't kept, nothing gets signed. So if a JavaScript function already takes parameters and returns a value, why bother writing these types down? Because without the written promise, whoever calls the function only learns what's coming back by actually running it and seeing; a typed signature tells you that before you ever call it, at compile time — Java already required a method signature, and TypeScript adds that same promise to JavaScript functions. The concrete QA payoff: pass a single object (not an array) by mistake into a `calculateScore(results: TestResult[]): number` function, and untyped JavaScript accepts it silently and computes the wrong thing inside; a typed signature flags that same mistake with a red squiggle in the IDE, before the test ever runs.

Micro Lab: TypeScript coding practice

Replace the TODO line with the critical line from the expected solution. This is not a real runtime; the goal is to reinforce writing the correct structure in a controlled way.

TypeScript function patterns

Give each parameter a type — wrong type passed means compile error

role = 'user' — one line instead of overloaded methods in Java

type Validator = (value: string) => boolean — use function as a value

Order the steps of designing a typed function:

Determine input types

Determine return type

Mark optional and default parameters

Document function type with type alias

In function createUser(email: string, role: "admin" | "user" = "user"), is createUser("alice@test.com") valid?

Yes — role is optional because it has a default value of "user"