Typescript

Job Interview Questions - Typescript

Core Type System

Base Types

interface Product {
	id: number;
	name: string;
	price: number;
	inStock: boolean;
	tags: string[];
	metadata: Record<string, any>;
}

Union and Intersection Types

type PaymentMethod = 'credit_card' | 'paypal' | 'bank_transfer';
type User = { name: string; email: string };
type Admin = { permissions: string[] };
type AdminUser = User & Admin;

Type Aliases and Interfaces

type ApiResponse<T> = {
	data: T;
	status: number;
	message: string;
};

interface UserProfile extends User {
	avatar?: string;
	lastLogin: Date;
}

Type Never

Functions And Methods

Function Types

type EventHandler<T> = (event: T) => void;
type ValidationRule<T> = (value: T) => string | null;

const validateEmail: ValidationRule<string> = (email) => {
	return email.includes('@') ? null : 'Invalid email';
}

Method Overloading

class Query Builder {
	find(id: number): Promise<User>;
	find(criteria: Partial<User>): Promise<User[]>;
	find(idOrCriteria: number | Partial<User>): Promise<User | User[]> {
		
	}
}

Optional and Default Parameters

function logMessage(
	message: string,
	level: 'info' | 'warn' | 'error' = 'info',
	timestamp?: Date
) {
	const time = timestamp || new Date();
	console.log(`[${level.toUpperCase()}] ${time.toISOString()}: ${message}`)
}

Advanced Type Features

Generics

class ApiClient<TBaseUrl extends string> {
	constructor(private baseUrl: TBaseUrl) {}
	
	async get<TResponse>(endpoint: string): Promise<ApiResponse<TResponse>> {
		const response = await fetch(`${this.baseUrl}${endpoint}`);
		return resonse.json();
	}
}

const userApi = new ApiClient('https://api.example.com/users');
const users = await userApi.get<User[]>('/');

Conditional Types

type ValidationResult<T> = T extends string 
	? { isValid: boolean; errors: string[] }
	: T extends number
	? { isValid: boolean; min?: number; max?: number }
	: { isValid: boolean };
	
function validate<T>(value: T): ValidationReasult<T> {
	// Type-safe validation based on input type
}

Mapped Types

type FormState<T> = {
	[K in keyof T]: {
		value: T[K];
		error?: string;
		touched: boolean;
	}
};

type UserFormState = FormState<{
	email: string;
	age: number;
	newsletter: boolean;	
}>;

// Results in:
// {
//  	email: { value: string; error?: string; touched: boolean };
//  	age: { value: number; error?: string; touched: boolean };
//  	newsletter: { value: boolean; error?: string; touched: boolean };
// }

Template Literal Types

type CCSUnit = 'px' | 'em' | 'rem' | '%';
type Size = `${number}${CSSUnit}`;
type Color = `#${string}` | `rgb(${number}, ${number}, ${number})`;

interface StyleProps {
	width?: Size;
	height?: Size;
	backgroundColor?: Color;
}

const button: StyleProps = {
	width: '100px', // valid
	height: '2rem', // valid
	backgroundColor: '#ff0000' // valid
	// backgroundColor: 'invalid' // type error
};

Utility Types


// User management system
interface User {
	id: number;
	email: string;
	password: string;
	profile: {
		firstName: string;
		lastName: string;
		avatar?: string;
	};
};

// For user registration (password optional initially)
type UserRegistration = Omit<User, 'id'> & {
	confirmPassword: string;
}

// For profile updates (all fields optional)
type ProfileUpdate = Partial<Pick<User, 'profile'>>;

// For public user data (no sensitive info)
type PublicUser = Omit<User, 'password'>;

Typescript generics