TypeScriptBasic types

Object types

A description of an object’s shape: what fields it has and of what type.

On this page

Example

#
TypeScript
function greet(user: { name: string; level: number }): string {
  return `Hi ${user.name}, you have level ${user.level}`
}

console.log(greet({ name: 'Mia', level: 4 }))
Result
Hi Mia, you have level 4

Definition and usage

#

An object type lists its properties together with their types: { name: string; level: number }. An object assigned to a variable like that must have every required field, with matching types.

For object literals, the compiler also checks for extra fields. A typo in a field name, like levle, gets reported instead of silently adding an unused property.

Object types that repeat throughout the code are worth naming with type or interface. You mark optional fields with a question mark, and read-only fields with the word readonly.

Syntax

#
Syntax
let object: { field: type; second?: type }

More examples

#
An extra field in the literal
TypeScript
greet({ name: 'Jack', levle: 3 })
// Error: Object literal may only specify known properties, and 'levle' does not exist in type '{ name: string; level: number; }'.

Good practices

#
  • When the same object shape shows up a second time, give it a name with type or interface.
  • Separate fields with semicolons or commas, but stay consistent across the whole project.

Related entries

#

Spotted a mistake or missing an example? Write to us.