TypeScript, a superset of JavaScript, enhances the type system and brings additional features to JavaScript, making it a powerful tool for building scalable and maintainable applications. This article will explore TypeScript Object Types, diving into topics like excess properties, type aliases, nested objects, optional properties, the readonly modifier, and intersection types. If you are new to TypeScript, it is recommended to go through this TypeScript Overview and the TypeScript Installation & Setup Guide before continuing.
Table of Contents
- Working with Object Types
- Excess Properties
- Creating Type Aliases
- Nested Objects
- Optional Properties
- The Readonly Modifier
- Intersection Types
- Exercise: Putting It All Together
- Conclusion
Working with Object Types
In TypeScript, object types are used to describe the structure of an object. They are defined using curly braces {}
and a comma-separated list of properties and their types. You can learn more about TypeScript type annotations in this Type Annotation Guide.
let user: { name: string; age: number } = {
name: "Alice",
age: 30,
};
Code language: JavaScript (javascript)
Excess Properties
TypeScript helps catch errors by checking for excess properties in object literals. When an object literal has properties that are not defined in the type, TypeScript will throw an error.
let person: { name: string; age: number } = {
name: "Bob",
age: 25,
occupation: "Developer", // Error: Object literal may only specify known properties
};
Code language: JavaScript (javascript)
Creating Type Aliases
Type aliases enable you to give a new name to a type. They can be helpful when dealing with complex object types or when you want to reuse a type across your codebase. Declare a type alias using the type
keyword.
type User = {
name: string;
age: number;
};
let user: User = {
name: "Carol",
age: 28,
};
Code language: JavaScript (javascript)
Nested Objects
Object types can also have nested objects. This allows you to create more complex structures by combining multiple objects.
type Address = {
street: string;
city: string;
zipCode: string;
};
type Person = {
name: string;
age: number;
address: Address;
};
let person: Person = {
name: "Dan",
age: 35,
address: {
street: "123 Main St",
city: "New York",
zipCode: "10001",
},
};
Code language: JavaScript (javascript)
Optional Properties
Sometimes, properties in an object may not always be present. You can define optional properties using a question mark ?
after the property name.
type Employee = {
name: string;
age: number;
department?: string;
};
let employee: Employee = {
name: "Eve",
age: 30,
};
Code language: JavaScript (javascript)
The Readonly Modifier
TypeScript provides a readonly
modifier, which prevents a property from being reassigned after it has been initialized.
type ImmutablePerson = {
readonly name: string;
readonly age: number;
};
let person: ImmutablePerson = {
name: "Frank",
age: 40,
};
person.name = "George"; // Error: Cannot assign to 'name' because it is a read-only property
Code language: JavaScript (javascript)
Intersection Types
Intersection types allow you to combine multiple types into one, creating a new type that has all the properties of the combined types. You can use the &
operator to create an intersection type.
type EmployeeInfo = {
position: string;
salary: number;
};
type FullEmployee = Person & EmployeeInfo;
let employee: FullEmployee = {
name: "Helen",
age: 45,
address: {
street: "456 Market St",
city: "Los Angeles",
zipCode: "90012",
},
position: "Manager",
salary: 80000,
};
Code language: JavaScript (javascript)
Exercise: Putting It All Together
Now, let’s put everything together in a small exercise. Create a type alias UserProfile
that represents a user’s profile with the following properties:
id
: a readonly numberusername
: a stringemail
: an optional stringaddress
: a nested object withstreet
,city
, andzipCode
propertiesisAdmin
: a boolean
Next, create a UserProfile
object that satisfies the type constraints.
Conclusion
In this article, we’ve explored the various aspects of TypeScript object types, including excess properties, type aliases, nested objects, optional properties, the readonly modifier, and intersection types. Understanding these concepts is crucial for writing clean, maintainable, and type-safe code in TypeScript. To further enhance your TypeScript skills, check out this guide on TypeScript Functions. Keep learning and experimenting with TypeScript to take your projects to the next level.