"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > TypeScript for Beginners, Part 3: Interfaces

TypeScript for Beginners, Part 3: Interfaces

Posted on 2025-03-23
Browse:863

TypeScript for Beginners, Part 3: Interfaces

This tutorial continues our TypeScript beginner series, building upon previous introductions to TypeScript features, installation, and IDE suggestions. The second tutorial covered TypeScript data types and their error-prevention benefits.

This part focuses on interfaces. We'll explore how interfaces, like x and Point (with width), and Cuboid (extending Point with length and height), help define object structures. The Cuboid example demonstrates specifying values for all properties and using a function to calculate volume.

It's crucial to note that interfaces are a TypeScript-specific feature, absent in JavaScript. Compiling the TypeScript code results in the following JavaScript equivalent:

function volumeCuboid(cuboid) {
    let volume = cuboid.length * cuboid.width * cuboid.height;
    console.log(`Volume: ${volume}`);
}

let cuboid = { x: -22, y: 28, width: 12, length: 32, height: 20 };

volumeCuboid(cuboid);
// Volume: 7680

The tutorial also touches upon intersection types, contrasting them with interface extension. We examine how to create a RoundedRectangle using existing types, highlighting the differences between merging multiple interface declarations (allowed) and redeclaring types (resulting in errors).

Key Takeaways:

This tutorial provides a foundation in TypeScript interfaces, emphasizing their role in writing robust code. You've learned to create interfaces with optional and read-only properties, and to utilize index signatures for adding dynamic properties beyond the initial interface definition. For deeper understanding, refer to the official TypeScript documentation.

The next tutorial will delve into TypeScript classes.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3