Objects
Objects are the fundamental way in which data and functions are grouped and passed around.
In the example above, the person
object has an implicit typing with a name
and age
key corresponding
to string
and number
. However, in virtually all cases, it is more useful to define the data structure of
JavaScript objects with an explicit TypeScript type.
Interfaces
The most common way to define the keys and values of an object is an interface
declaration.
Optional keys
Add a ?
after a key name to mark it as optional.
If a key is not marked as optional, it is required. An object that is missing a required key will generate a TypeScript error.
Required
Convert all keys to required Required
Partial
Convert keys to optional
Readonly
Index signatures
You can define dynamic keys for index signatures.
interface Dictionary { [key: string]: string;}const translations: Dictionary = { hello: "Hola", goodbye: "Adiós",};
Using Record K, V for Object Types A utility type to define objects with fixed key-value types:
type UserRoles = Record<string, "admin" | "user">;const roles: UserRoles = { alice: "admin", bob: "user",};
Extending and Merging Object Types
interface Animal { name: string;}interface Dog extends Animal { breed: string;}const myDog: Dog = { name: "Buddy", breed: "Golden Retriever" };
Type Composition
type Animal = { name: string };type Dog = Animal & { breed: string };const myDog: Dog & { friend: string } = { name: "Buddy", breed: "Golden Retriever", friend: "best"}