⏱️5 min read · 978 words
TypeScript interview questions in 2026 test your understanding of the type system, generics, advanced patterns, and integration with React and Node.js. This guide covers the most commonly asked TypeScript questions at both junior and senior levels.
Core TypeScript Questions
1. What is the difference between interface and type alias?
// Interface — can be merged (declaration merging), preferred for objects
interface User {
id: number;
name: string;
}
// Extend interface
interface AdminUser extends User {
role: 'admin';
}
// Declaration merging (unique to interface)
interface User {
email: string; // adds to existing interface
}
// Type alias — more flexible, supports unions and intersections
type ID = string | number;
type Status = 'pending' | 'active' | 'inactive';
type ApiResponse<T> = { data: T; error: string | null; };
// Intersection
type AuthUser = User & { token: string };
// When to use:
// interface: for objects, especially when extending or merging
// type: for unions, intersections, primitives, tuples
2. Explain generics with a real example
// Generic function — works with any type
function first<T>(items: T[]): T | undefined {
return items[0];
}
const num = first([1, 2, 3]); // type: number | undefined
const str = first(['a', 'b']); // type: string | undefined
// Generic with constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: 'Alice', age: 30 };
const name = getProperty(user, 'name'); // type: string
// getProperty(user, 'foo'); // Error! 'foo' not in keyof User
// Generic class
class Repository<T extends { id: number }> {
private items: T[] = [];
add(item: T): void { this.items.push(item); }
findById(id: number): T | undefined {
return this.items.find(i => i.id === id);
}
getAll(): T[] { return [...this.items]; }
}
const userRepo = new Repository<User>();
userRepo.add({ id: 1, name: 'Alice' });
3. What are utility types? Give examples
interface User {
id: number;
name: string;
email: string;
password: string;
role: 'admin' | 'user';
}
// Partial — all optional
type UserUpdate = Partial<User>;
// Required — all required (reverse of Partial)
type StrictUser = Required<User>;
// Pick — select fields
type PublicUser = Pick<User, 'id' | 'name' | 'email'>;
// Omit — exclude fields
type CreateUserInput = Omit<User, 'id'>;
type SafeUser = Omit<User, 'password'>;
// Readonly
type ImmutableUser = Readonly<User>;
// Record — map type
type UsersByRole = Record<'admin' | 'user', User[]>;
// Extract / Exclude
type StringOrNumber = string | number | boolean;
type OnlyString = Extract<StringOrNumber, string>; // string
type NoBoolean = Exclude<StringOrNumber, boolean>; // string | number
// ReturnType / Parameters
async function fetchUser(id: number): Promise<User> { /* ... */ return {} as User; }
type FetchResult = Awaited<ReturnType<typeof fetchUser>>; // User
type FetchArgs = Parameters<typeof fetchUser>; // [number]
// NonNullable
type MaybeUser = User | null | undefined;
type DefiniteUser = NonNullable<MaybeUser>; // User
4. Explain the `unknown` type vs `any`
// any — disables type checking (avoid!)
let a: any = 'hello';
a.toUpperCase(); // OK (even if string)
a.nonExistent(); // No error! Dangerous!
// unknown — type-safe alternative to any
let b: unknown = 'hello';
// b.toUpperCase(); // Error! Must narrow first
// b.nonExistent(); // Error!
// Must narrow unknown before use
if (typeof b === 'string') {
b.toUpperCase(); // OK — narrowed to string
}
// Real use case: typed error handling
async function fetchData(): Promise<unknown> {
const r = await fetch('/api/data');
return r.json();
}
const data = await fetchData();
if (typeof data === 'object' && data !== null && 'users' in data) {
console.log((data as { users: User[] }).users);
}
5. What are mapped types?
// Map over keys of an existing type
type Optional<T> = {
[K in keyof T]?: T[K];
};
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
type ReadonlyUser = {
readonly [K in keyof User]: User[K];
};
// Conditional mapped type — change type based on condition
type NonNullableProps<T> = {
[K in keyof T]-?: NonNullable<T[K]>; // -? removes optional
};
// Key remapping (TS 4.1+)
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<User>;
// { getId: () => number; getName: () => string; ... }
6. Template literal types
type EventName = 'click' | 'focus' | 'blur';
type Handler = `on${Capitalize<EventName>}`;
// 'onClick' | 'onFocus' | 'onBlur'
type Route = '/users' | '/posts' | '/comments';
type ApiRoute = `${Route}/${number}`;
// '/users/1' | '/posts/2' etc.
// Real use case: CSS properties
type Side = 'top' | 'bottom' | 'left' | 'right';
type CSSPadding = `padding-${Side}`;
// 'padding-top' | 'padding-bottom' | 'padding-left' | 'padding-right'
// Event emitter with type safety
type Events = {
'user:created': { user: User };
'order:placed': { orderId: string; total: number };
};
declare function emit<K extends keyof Events>(event: K, data: Events[K]): void;
emit('user:created', { user: { id: 1, name: 'Alice' } }); // type-safe!
7. Discriminated unions
type Result<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E };
function handleResult<T>(result: Result<T>) {
if (result.success) {
console.log(result.data); // TypeScript knows: data exists
} else {
console.error(result.error); // TypeScript knows: error exists
}
}
// Shape discriminated union
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rectangle'; width: number; height: number }
| { kind: 'triangle'; base: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle': return Math.PI * shape.radius ** 2;
case 'rectangle': return shape.width * shape.height;
case 'triangle': return 0.5 * shape.base * shape.height;
}
}
TypeScript interview success: understand the type system deeply (not just syntax), explain why generics enable code reuse, know common utility types by heart, and demonstrate conditional + mapped types for advanced questions. TypeScript interviews increasingly test React+TypeScript integration — practice typing hooks, props, and event handlers.
📚 You might also like
🔗 Share this article




✍️ Leave a Comment