Object Types and Type Annotations


Object Types and Type Annotations#
Objects are a core part of JavaScript and TypeScript. Typing objects correctly helps catch errors early and makes your code more readable and maintainable.
Defining Object Types Inline
You can define the shape of an object inline using type annotations:
function printPerson(person: { name: string; age: number }): void {
console.log(`${person.name} is ${person.age} years old.`);
}
printPerson({ name: "Alice", age: 30 });This defines an object with name as a string and age as a number.
Nested Objects
Objects can contain nested objects, which you can type inline as well:
type Address = {
street: string;
city: string;
postalCode: string;
};
function printAddress(address: {
street: string;
city: string;
postalCode: string;
}): void {
console.log(`${address.street}, ${address.city} - ${address.postalCode}`);
}
const homeAddress: Address = {
street: "123 Main St",
city: "Anytown",
postalCode: "12345",
};
printAddress(homeAddress);You can also nest inline types directly:
function printPersonWithAddress(person: {
name: string;
age: number;
address: { street: string; city: string; postalCode: string };
}): void {
console.log(
`${person.name} lives at ${person.address.street}, ${person.address.city}`
);
}Object Literals
When you create an object literal, TypeScript infers its type based on the properties:
const car = {
make: "Toyota",
model: "Corolla",
year: 2020,
};You can explicitly type object literals to ensure they conform to a specific shape:
const car: { make: string; model: string; year: number } = {
make: "Toyota",
model: "Corolla",
year: 2020,
};Best Practices
- Use type aliases or interfaces (covered later) for reusable object types.
- Prefer explicit typing for function parameters and return types.
- Use nested types or aliases for complex objects to improve readability.
- Leverage TypeScript’s type inference when possible for object literals.
Tip: Inline object types are great for quick, one-off types but consider interfaces or type aliases for complex or reused shapes.
Common Mistakes
- Forgetting to type nested objects, leading to implicit
any. - Mismatching property names or types in object literals.
- Overusing inline types, which can reduce readability in large codebases.
Next Steps
Next, learn about interfaces in TypeScript to define contracts for objects with optional and readonly properties.
Questions about object types or type annotations? Share your thoughts or examples in the comments!