TypeScript Wiki
Give a parameter a default value
Tag builds a label from its text and color. Leave out the second argument and the parameter supplies gray.
You passed red as the second argument, so color holds red.
- What you sent
Tag("New", "red")- What Tag returned
Tag.ts
export function Tag(text: string, color ) {
return text + " (" + color + ")";
} This initializer runs when the color argument is missing or undefined.
Compare two calls
Tag("New") → "New (gray)"
Tag("New", "red") → "New (red)" Reading the syntax
text: string- The first argument supplies the sticker text. It is required.
color = "gray"- If the second argument is omitted or undefined, color starts as gray. TypeScript infers string from this default.
return- Both calls reach the same line. It joins the text and the color chosen when the function was called.
What if you pass an empty string?
Tag("New", "") → "New ()" An empty string is a supplied value, so the default is skipped.