Skip to content
MacTokyo.
日本語

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.

Pick a sticker color

You passed red as the second argument, so color holds red.

What you sent
Tag("New", "red")
What Tag returned
"New (red)"

Tag.ts

export function Tag(text: string, color ) {
  return text + " (" + color + ")";
}

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.

Related: optional props Union types with AvatarProps