TypeScript Object Types (original) (raw)
Last Updated : 23 Jan, 2025
**TypeScript object types define the structure of objects by specifying property types, ensuring type safety and clarity when passing objects as function parameters.
- Optional properties, denoted with a ? provide flexibility for objects with varying properties.
- This approach enhances code robustness by allowing the omission of certain properties when appropriate. JavaScript ``
interface Person { name: string; age: number; address?: string; // Optional property }
function greet(person: Person): string {
return Hello, ${person.name}!
;
}
const user: Person = { name: "Alice", age: 30 };
console.log(greet(user));
``
- The Person interface defines an object type with name and age as required properties, and address as an optional property.
- The greet function accepts a parameter of type Person and returns a greeting message.
- The user object adheres to the Person interface, and the greet function is called with this object.
**Output:
Hello, Alice!
**More Example of TypeScript Object Types
**Defining a Car Object
JavaScript ``
interface Car { make: string; model: string; year: number; electric?: boolean; // Optional property }
const myCar: Car = { make: "Tesla", model: "Model S", year: 2022, electric: true };
console.log(I drive a <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>m</mi><mi>y</mi><mi>C</mi><mi>a</mi><mi>r</mi><mi mathvariant="normal">.</mi><mi>y</mi><mi>e</mi><mi>a</mi><mi>r</mi></mrow><annotation encoding="application/x-tex">{myCar.year} </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8778em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathnormal">m</span><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="mord mathnormal" style="margin-right:0.07153em;">C</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord">.</span><span class="mord mathnormal">ye</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span></span></span></span></span>{myCar.make} ${myCar.model}.
);
``
- The Car interface defines an object type with make, model, and year as required properties, and electric as an optional property.
- The myCar object adheres to the Car interface, specifying values for all properties.
**Output:
I drive a 2022 Tesla Model S.
Nested Object Types for a Book
JavaScript ``
interface Author { name: string; birthYear: number; }
interface Book { title: string; author: Author; pages: number; genre?: string; // Optional property }
const myBook: Book = { title: "TypeScript Basics", author: { name: "Jane Doe", birthYear: 1980 }, pages: 350 };
console.log(${myBook.title} by ${myBook.author.name}
);
``
- The Author interface defines the structure for an author object.
- The Book interface includes a nested author property of type Author, along with other properties.
- The myBook object conforms to the Book interface, including a nested author object.
**Output:
TypeScript Basics by Jane Doe
Function Parameter with Object Type
JavaScript ``
interface Rectangle {
width: number;
height: number;
}
function calculateArea(rect: Rectangle): number {
return rect.width * rect.height;
}
const myRectangle: Rectangle = {
width: 10,
height: 5
};
console.log(Area: ${calculateArea(myRectangle)}
);
``
- The Rectangle interface defines the structure for a rectangle object.
- The calculateArea function accepts a parameter of type Rectangle and returns the area.
- The myRectangle object adheres to the Rectangle interface and is passed to the function.
**Output:
Area: 50
Best Practices for Using TypeScript Object Types
- **Prefer Interfaces for Object Type Definitions: Use interface to define object shapes, as they are extendable and provide clear intent.
- **Utilize Type Aliases for Complex Types: Employ type aliases when defining complex types, such as unions or intersections, to enhance code readability.
- **Leverage Readonly Properties: Mark properties as readonly to prevent unintended mutations, ensuring data integrity.
- **Avoid Excessive Typing: Rely on TypeScript's type inference where possible to reduce redundancy and maintain cleaner code.