今日已更新 233 条资讯 | 累计 20205 条内容
关于我们

Structuring TypeScript: Interfaces, Type Aliases, Enums, and Object Types

Ramesh S 2026年06月19日 11:27 4 次阅读 来源:Dev.to

Structuring TypeScript: Interfaces, Type Aliases, Enums, and Object Types You've learned TypeScript's primitive types and the basics of type inference here . Now it's time to model real-world data — users, orders, API responses, configuration objects. That's where interfaces, type aliases, and enums come in. These three features are what make TypeScript genuinely powerful for building applications. Let's dig in. Object Types: Describing the Shape of Data Before we get to interfaces, let's understand object types. When you want to describe the structure of an object, you define what properties it has and what types those properties are: // Inline object type annotation function displayUser ( user : { name : string ; age : number ; email : string }): void { console . log ( ` ${ user . name } ( ${ user . age } ) — ${ user . email } ` ); } This works, but it's messy to repeat everywhere. That's why we use type aliases and interfaces to name and reuse these shapes. Type Aliases: Naming a Type A type alias gives a name to any type — primitives, unions, objects, or combinations: // Alias for a primitive union type ID = string | number ; // Alias for an object shape type User = { id : ID ; name : string ; age : number ; email : string ; }; // Now use it anywhere const user : User = { id : 1 , name : " Ramesh " , age : 31 , email : " ramesh@example.com " , }; function getUser ( id : ID ): User { // ... fetch user logic } Type aliases are flexible — they can represent almost anything. Interfaces: Defining Object Contracts An interface is specifically designed to describe the shape of an object. Syntax is slightly different: interface User { id : number ; name : string ; age : number ; email : string ; } const user : User = { id : 1 , name : " Ramesh " , age : 31 , email : " ramesh@example.com " , }; Optional and Readonly Properties Properties can be marked as optional ( ? ) or read-only ( readonly ): interface UserProfile { readonly id : number ; // Can't be changed after cre

本文内容来源于互联网,版权归原作者所有
查看原文