Skip to content
MacTokyo.
日本語

TypeScript Wiki

Make a prop optional

Tag takes an object with sticker text and an optional color. It returns a label like New (red), using gray when you leave the color out.

Pick a sticker color

You sent red. Tag skips the gray line and uses your red in the last return.

What you sent
Tag({ text: "New", color: "red" })
What Tag returned
"New (red)"

Tag.ts

type TagProps = {
  text: string;
  color: string;
};

export function Tag(props: TagProps) {
  if () {
    return props.text + " (gray)";
  }
  return props.text + " (" + props.color + ")";
}

Where I got stuck

I forgot the ? on color, so TypeScript required a color on every call. I also tried reading color by itself. The parameter is an object named props, so I needed props.color.

Reading the syntax

type TagProps
Names the object type the function accepts.
text: string
Every call needs text. The colon introduces its type, string.
color?: string
The ? after the property name lets callers omit color. A supplied color can be a string.
props: TagProps
The parameter is named props and has type TagProps. The dot in props.color reads a property of that object.
props.color === undefined
Omitting color makes this check true, so the first return ends the call. Providing a color takes the final return.
If you replace gray with blue, which calls change?

Only calls that omit the color change. For example, New (gray) becomes New (blue).

Give a parameter a default value Union types with AvatarProps