TypeScript Cheat Sheet/Annotate object shapes

Describe the expected properties of an object.

Section: Primitive Types and Annotations

Annotate object shapes

typescript
typescript
const user: { id: number; name: string; admin?: boolean } = {
  id: 1,
  name: "Ada"
};
Explanation

Optional properties use `?` in object type annotations.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Primitive Types and Annotations
Annotate basic variables
Explicitly type strings, numbers, and booleans.
OpenIn sheettypescriptsame section
Type arrays
Declare arrays using `T[]` or `Array<T>`.
OpenIn sheettypescriptsame section
Use a union type
Allow multiple possible primitive types.
OpenIn sheettypescriptsame section
Restrict values with literal unions
Use exact string values for safer APIs.
OpenIn sheettypescriptsame section
Rely on inference
Let TypeScript infer common variable types.
OpenIn sheettypescriptsame section
Freeze literals with `as const`
Preserve readonly literal values for objects and arrays.
OpenIn sheettypescriptsame section