
Leif Le
September 11, 2025
25 min read
TypeScript for Frontend Dev Interviews
Typescript
Both interface and type can describe the shape of an object, but there are some differences:
1. Interface vs Type
Both interface and type can describe the shape of an object, but there are some differences:
β Similarities:
interface IUser {
id: number;
name: string;
}
type User = {
id: number;
name: string;
};
Both can be used:
const u1: IUser = { id: 1, name: "Alice" };
const u2: User = { id: 2, name: "Bob" };
β Differences:
- Extend/Implement:
- interface is extendable and works better with classes.
- type can use intersection & to combine.
interface Person { name: string; }
interface Developer extends Person { skills: string[]; }
type Animal = { species: string };
type Dog = Animal & { breed: string };
- Reopening / Declaration Merging:
- Interfaces can be reopened (add properties later).
- Types cannot.
interface Window { title: string; }
interface Window { version: string; } // merged automatically
// type cannot do this
- Utility Types / Complex Constructs:
- type can define unions, tuples, mapped types.
- interface cannot.
type Status = "loading" | "success" | "error";
type ApiResponse<T> = { data: T } | { error: string };
π Rule of thumb (for interviews):
- Use interface when describing object shapes and OOP-style code.
- Use type when building unions, advanced types, or aliases.
2. Extending Interfaces
Typical interview question:
interface User {
id: number;
name: string;
}
interface Admin extends User {
role: "admin";
}
const admin: Admin = { id: 1, name: "Quang", role: "admin" };
π Shows you understand inheritance in types.
Equivalent with type:
type User = { id: number; name: string };
type Admin = User & { role: "admin" };
3. Generics
Generics make your code reusable and type-safe.
Example 1: Generic Function
function identity<T>(value: T): T {
return value;
}
const str = identity<string>("hello");
const num = identity(123); // TS infers T = number
Example 2: Generic Interface
interface ApiResponse<T> {
data: T;
error?: string;
}
const userResponse: ApiResponse<{ id: number; name: string }> = {
data: { id: 1, name: "Quang" },
};
Example 3: Constraints
function getLength<T extends { length: number }>(item: T): number {
return item.length;
}
getLength("hello"); // β
string has length
getLength([1, 2, 3]); // β
array has length
// getLength(123) β number has no length
Example 4: React + Generics (interview classic)
function List<T>({ items, render }: { items: T[]; render: (item: T) => JSX.Element }) {
return <ul>{items.map(render)}</ul>;
}
<List
items={["Alice", "Bob"]}
render={(name) => <li key={name}>{name}</li>}
/>;
4. Practice Interview Questions
- Whatβs the difference between type and interface? Which one allows merging?
- Extend an interface User into Admin.
- Write a generic function getFirst<T>(arr: T[]): T.
- Create a generic ApiResponse<T> type for API calls.
- Why use generics instead of any?