TypeScript Wiki
Union types with AvatarProps
Mac’s avatar comes in three sizes. Change size to see the avatar grow or shrink, then try xl to see which line TypeScript flags.
Avatar.ts
type AvatarProps = {
name: string;
size: "sm" | "md" | "lg";
rounded?: "circle" | "square";
};
const a: AvatarProps = { name: "Mac", size: "sm" }; type AvatarProps = {
name: string;
size: "sm" | "md" | "lg";
rounded?: "circle" | "square";
};
const a: AvatarProps = { name: "Mac", size: "md" }; type AvatarProps = {
name: string;
size: "sm" | "md" | "lg";
rounded?: "circle" | "square";
};
const a: AvatarProps = { name: "Mac", size: "lg" }; type AvatarProps = {
name: string;
size: "sm" | "md" | "lg";
rounded?: "circle" | "square";
};
const a: AvatarProps = { name: "Mac", size: "xl" }; Where I got stuck
In my November 25 notes I first wrote size: number. I wanted named choices, like variants in Figma. The type lists those names. This demo draws sm at 40 px, md at 64 px, and lg at 96 px.
Reading the syntax
"sm" | "md" | "lg"- Each quoted word is a literal type. The bars join them into a union, so size accepts any one of the three.
rounded?: "circle" | "square"- The question mark lets you omit the shape. This preview draws a circle when shape is omitted.