← Back to TypeScript Menu | 🏠 Hub
// interface = object ရဲ့ shape define
interface User {
id: number;
name: string;
email: string;
role: "admin" | "user";
phone?: string; // ? = optional field
readonly createdAt: Date; // readonly = can't change after creation
}
// Use interface
const user: User = {
id: 1,
name: "Ko Ko",
email: "ko@test.com",
role: "admin",
createdAt: new Date()
};
user.name = "Ma Ma"; // ✅ OK
user.createdAt = new Date(); // ❌ Error: readonly!
user.phone = "09123"; // ✅ optional OK
user.age = 25; // ❌ Error: not in interface
interface Animal {
name: string;
sound(): string;
}
// Extend
interface Dog extends Animal {
breed: string;
}
// Declaration merging
// (can add to existing interface)
interface User { id: number; }
interface User { name: string; }
// merged: { id, name }
type Animal = {
name: string;
sound(): string;
};
// Extend (intersection)
type Dog = Animal & {
breed: string;
};
// Can't merge
// type User = { id: number }
// type User = { name: string }
// ❌ Duplicate identifier error!
// Can do unions
type ID = string | number;
| interface | type | |
|---|---|---|
| Objects | ✅ | ✅ |
| Primitives/Union | ❌ | ✅ |
| Declaration merging | ✅ | ❌ |
| Extends/implements | ✅ extends | ✅ & intersection |
| Recommended | Object shapes, class contracts | Unions, aliases, utilities |
interface BaseEntity {
id: number;
createdAt: Date;
updatedAt: Date;
}
interface User extends BaseEntity {
name: string;
email: string;
role: "admin" | "user";
}
interface Post extends BaseEntity {
title: string;
body: string;
userId: number;
tags?: string[];
}
// Intersection type (type alias)
type AdminUser = User & {
permissions: string[];
lastLogin: Date;
};
// Partial — all fields optional (DTO for update)
type UpdateUser = Partial<User>;
// { id?: number; name?: string; email?: string; ... }
// Pick — select some fields
type UserPreview = Pick<User, 'id' | 'name'>;
// Omit — exclude some fields
type CreateUser = Omit<User, 'id' | 'createdAt' | 'updatedAt'>;
// Required — all optional → required
type RequiredUser = Required<Partial<User>>;
interface Address {
street: string;
city: string;
zip?: string;
country: string;
}
interface Profile {
avatar?: string;
bio?: string;
social?: {
twitter?: string;
github?: string;
linkedin?: string;
};
}
interface User {
id: number;
name: string;
email: string;
address: Address;
profile: Profile;
tags: string[];
scores: Record<string, number>; // { math: 95, english: 88 }
}
// Record type — key-value map
type LangScore = Record<string, number>;
const scores: LangScore = { javascript: 90, python: 85 };
// Index signature — any string key
interface StringMap {
[key: string]: string;
}
const labels: StringMap = { hello: "ဟဲလို", bye: "နှုတ်ဆက်" };
← TS 01 | Next: TS 03 → Functions →