Object Types
Typing object structures
Introduction
In this lesson, you'll learn about object types in TypeScript. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with typing object structures.
TypeScript has its own approach to typing object structures, which we'll explore step by step.
The TypeScript Way
Let's see how TypeScript handles this concept. Here's a typical example:
// TypeScript objects with inline type
const user: {
name: string;
age: number;
email: string;
} = {
name: "Alice",
age: 30,
email: "alice@example.com"
};
function printUser(user: { name: string; age: number }): void {
console.log(user.name, user.age);
}
// TypeScript prevents unknown properties
// user.newProperty = "anything"; // Error!Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
// JavaScript objects
const user = {
name: "Alice",
age: 30,
email: "alice@example.com"
};
function printUser(user) {
console.log(user.name, user.age);
}
// Objects can have any shape
user.newProperty = "anything";You may be used to different syntax or behavior.
Object types define property names and types
You may be used to different syntax or behavior.
Properties are separated by semicolons or commas
You may be used to different syntax or behavior.
Unknown properties cause compile errors
Step-by-Step Breakdown
1. Inline Object Types
You can define object types inline, but this can get verbose.
function greet(person) {
return "Hello " + person.name;
}function greet(person: { name: string }): string {
return "Hello " + person.name;
}2. Optional Properties
Use ? to mark properties that may not exist.
type User = {
name: string;
age: number;
email?: string; // optional
};3. Readonly Properties
Use readonly to prevent property reassignment.
type Config = {
readonly apiKey: string;
readonly baseUrl: string;
};
const config: Config = { apiKey: "xxx", baseUrl: "..." };
// config.apiKey = "new"; // Error!Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- Object types define property names and types
- Properties are separated by semicolons or commas
- Unknown properties cause compile errors
Key Takeaways
- Object types list properties with their types
- Use ? for optional properties
- Use readonly to prevent reassignment
- Type aliases make object types reusable