Quick overview
- Arrays: ordered collections of values (e.g., a list of duck names).
- Objects: group related values into a single item (e.g., name, age, type, color).
- Combining both: arrays of objects let you model collections of richly-described items (e.g., a flock of ducks).
Arrays
Declare an array of strings in TypeScript using either bracket syntax or the genericArray<T> form. Both are equivalent; pick the style your team prefers.
string.
Table — common array syntaxes
Useful array operations (examples)
Objects
When you need to store multiple properties about a single duck (for example:name, age, type, and color), use an object.
Object literal (untyped):
interface for stronger guarantees:
type alias if you prefer:
Accessing properties
Use dot notation for the common case:{ name: 'Daffy', age: 3, type: 'Mallard', color: 'Black' }:
- Keys (properties):
name,age,type,color - Values:
'Daffy',3,'Mallard','Black'
Putting arrays and objects together
Most real-world data models use arrays of objects. For example, a typed collection ofDuck objects:
- Find an item:
flock.find(d => d.name === 'Howard') - Filter:
flock.filter(d => d.age > 2) - Map to a new shape:
flock.map(d => d.name)
Note about const and mutation
Declaring a variable with If you need immutability at the type level, prefer
const prevents reassignment of the identifier but does not make the object or array immutable. You can still modify properties or change the array contents:readonly properties and readonly arrays (e.g., readonly Duck[] or ReadonlyArray<Duck>).Summary
- Use
T[]orArray<T>to type arrays. - Use object literals for single items and
interfaceortypeto enforce a shape for objects. - Combine arrays and objects to model lists of rich items (e.g.,
Duck[]). constprotects the binding, not the contents — usereadonlyfor immutability when appropriate.