Member-only story

TypeScript: Create Custom Types

Abhishek Wadalkar
3 min readJust now

--

TypeScript allows developers to create custom types, which improve code readability, enforce structure, and make applications more robust. Custom types help define reusable and meaningful data structures that fit your specific project needs.

In this post, we’ll explore how to create custom types and when to use them for better TypeScript development.

How to Create a Custom Type?

There are two main ways to define custom types in TypeScript:
1️⃣ Using type (Type Alias)
2️⃣ Using interface

1️⃣ Creating a Custom Type with type (Type Alias)

The type keyword allows you to define a custom name for a data structure.

type User = {
id: string;
name: string;
age: number;
};

🔹 Now, we can use User as a type for objects:

const user1: User = { id: "1", name: "Alice", age: 30 };
console.log(user1.name); // Output: Alice

2️⃣ Creating a Custom Type with interface

An interface works similarly to a type, but it is best used for defining object shapes.

interface User {
id: string;
name: string;
age: number;
}

🔹 Now, we can use User as a type:

const user2: User = { id: "2", name: "Bob", age: 25 };
console.log(user2.age); // Output: 25

--

--

Abhishek Wadalkar
Abhishek Wadalkar

Written by Abhishek Wadalkar

Passionate Frontend developer with 4 years experience, crafting seamless, user-centric web experiences. Exploring the world of web development and constantly.

No responses yet