← TypeScript Foundations
11 / 25
Lesson 11 — Optional params
Optional parameters
Adding ? after a parameter name (msg?: string) makes it optional: callers may leave it out, and then its value is undefined. Inside the function you give it a fallback — with ?? — or you write a default value (msg: string = "Hi") instead, which makes it optional automatically.
function tag(text: string, color?: string) {
return text + " (" + (color ?? "grey") + ")";
}
Why it matters: optional inputs keep calls short for the common case without losing type checks.
Want it another way?
Task
msg is optional. Use "Hi" when it is missing, so the program prints Hi Sam and Hello Ann.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
Test your knowledge
A quick 3-question quiz on this lesson — instant feedback.