Introduction
Object types help us describe the shape of data clearly. They make sure we use the right properties and values in our programs.
Object types help us describe the shape of data clearly. They make sure we use the right properties and values in our programs.
type Person = {
name: string;
age: number;
};Use type keyword to define a new object type.
Inside curly braces, list property names with their types.
Car type with make and year properties.type Car = {
make: string;
year: number;
};Book type with three properties.type Book = {
title: string;
author: string;
pages: number;
};This program defines a Person type and a function that uses it. It then creates a user object and greets the user.
type Person = {
name: string;
age: number;
};
function greet(person: Person) {
console.log(`Hello, ${person.name}! You are ${person.age} years old.`);
}
const user: Person = { name: "Alice", age: 30 };
greet(user);Object types help catch errors early by checking property names and types.
They make your code easier to read and understand.
Object types describe the shape of data with named properties.
They help prevent mistakes by enforcing correct property use.
Using object types makes your code clearer and safer.
type keyword followed by property names and types inside curly braces.type Person = { name: string; age: number; };. Others are function or array syntax, not object types.type Car = { make: string; year: number };
const myCar: Car = { make: "Toyota", year: 2020 };
console.log(myCar.year);Car expects properties make (string) and year (number). The object assigned matches this.myCar.year prints the number 2020, the value assigned to year.type User = { username: string; age: number };
const user: User = { username: "Anna" };User requires both username and age properties.username, missing age, causing a TypeScript error.title (string) and optional year (number). Which object type correctly describes this?? after the property name.title is required (string), and year is optional (number). type Movie = { title: string; year?: number; }; matches this exactly.Pass the test and this pattern moves unknown