TypeScript Interfaces and Type Aliases
Edited by Dev Kilaru, Senior Data Analyst. How we make our content
Introduction
A big part of TypeScript is describing the shape of your data. Interfaces and type aliases both let you name a shape and reuse it, so the compiler can check that objects have the properties you expect. This tutorial covers both and their differences.
Prerequisites
- A TypeScript project you can compile
- Basic familiarity with objects and functions in JavaScript
Step-by-Step Guide
Step 1: Describe an object with an interface
List each property and its type. Add ? to make a property optional and readonly to prevent reassignment.
interface User {
readonly id: number;
name: string;
email?: string;
}
const user: User = { id: 1, name: "Ava" };
// user.id = 2;
// Error: Cannot assign to 'id' because it is a read-only property.Step 2: Extend an interface
An interface can build on another with extends, adding more properties.
interface Admin extends User {
permissions: string[];
}
const admin: Admin = { id: 2, name: "Ben", permissions: ["edit", "delete"] };Step 3: Use type aliases
A type alias names any type, including unions and object shapes.
type ID = string | number;
type Point = { x: number; y: number };
function describe(id: ID): string {
return "ID: " + id;
}Step 4: Use shapes in function signatures
Annotating parameters with your interface makes calls type-checked and gives you autocomplete.
function printUser(user: User): void {
console.log(user.name + (user.email ? " <" + user.email + ">" : ""));
}
printUser({ id: 3, name: "Cy", email: "cy@example.com" });FAQs
- Should I use interface or type?
- Both describe object shapes. Interfaces can be extended and merged by redeclaring them. Type aliases can also name unions, primitives, and tuples. Many teams use interface for object shapes and type for unions; pick a convention and stay consistent.
- Are TypeScript types checked at runtime?
- No. Types exist only at compile time and are erased from the JavaScript output. Validate data that comes from outside your program, such as API responses, separately.
Summary
Use interfaces and type aliases to give your data a name and a shape. Mark optional and read-only properties explicitly, and reuse shapes across function signatures.
Related tutorials
- Schedule and Debug Shell Scripts: cron, bash -x, and Portability
- Shell Scripting Project: A Backup Script with Rotation and a Log Report
- Writing Safe Bash Scripts: set -euo pipefail, getopts, and trap
- Shell Pipes, Redirection, grep, sed, and awk for Text Processing
- Bash Loops, Arrays, and Functions Explained
Comments
Log in or create a free account to join the discussion.