1. What is TypeScript and how does it differ from JavaScript?
TypeScript is a superset of JavaScript developed by Microsoft. It adds optional static typing and class-based object-oriented programming to JavaScript.
Key differences:
- Typing: JavaScript is dynamically typed (types are checked at runtime). TypeScript is statically typed (types are checked at compile time).
- Compilation: TypeScript must be transpiled into JavaScript to run in a browser or Node.js environment. JavaScript runs directly.
- Early Error Detection: TypeScript catches type-related errors during development, significantly reducing runtime crashes.
![]()
2. What is the difference between an interface and a type alias?
Both are used to define custom types, but they have subtle differences:
- Interfaces: Are specifically used to describe the shape of objects. They support declaration merging (defining the same interface multiple times will merge their properties). They are generally preferred for public API definitions.
- Type Aliases: Can represent any type, including primitives, unions, and intersections. They do not support declaration merging.
// Interface
interface User { name: string; }
interface User { age: number; } // Merges: { name: string; age: number }
// Type
type Point = { x: number; y: number };
type ID = string | number; // Union types cannot be done with interfaces
3. Explain the difference between any and unknown.
any: Completely disables TypeScript's type checking for that variable. You can access any property or call any method on it, which can lead to runtime errors. It should be avoided when possible.unknown: A safer alternative toany. It represents any value, but forces you to perform a type check (type narrowing) before you can perform operations on it.
let valueAny: any = "hello";
valueAny.foo(); // Compiles fine, but crashes at runtime
let valueUnknown: unknown = "hello";
// valueUnknown.foo(); // Error: Object is of type 'unknown'
if (typeof valueUnknown === "string") {
console.log(valueUnknown.toUpperCase()); // Works perfectly
}
4. What are Generics in TypeScript?
Generics allow you to create reusable components (functions, classes, interfaces) that can work with a variety of data types rather than a single one, while still maintaining strict type safety.
// 'T' is a generic type parameter
function identity<T>(arg: T): T {
return arg;
}
let num = identity<number>(42); // Returns number
let str = identity<string>("hello"); // Returns string
5. What are Union and Intersection types?
- Union Types (
|): Allow a variable to hold values of multiple different types. It means "this OR that". - Intersection Types (
&): Combine multiple types into a single type that has all the properties of the combined types. It means "this AND that".
// Union
let status: "success" | "error" | "loading";
// Intersection
interface HasName { name: string; }
interface HasAge { age: number; }
type Person = HasName & HasAge; // Must have both name and age
6. Explain common Utility Types: Partial, Readonly, Pick, and Omit.
TypeScript provides built-in utility types to facilitate common type transformations:
Partial<T>: Makes all properties of typeToptional.Readonly<T>: Makes all properties of typeTread-only (cannot be reassigned).Pick<T, K>: Creates a type by picking specific propertiesKfrom typeT.Omit<T, K>: Creates a type by removing specific propertiesKfrom typeT.
interface Todo {
title: string;
description: string;
completed: boolean;
}
type OptionalTodo = Partial<Todo>; // All properties optional
type TodoPreview = Pick<Todo, "title" | "completed">; // Only title and completed
type TodoWithoutDesc = Omit<Todo, "description">; // Removes description
7. Explain the difference between void and never types.
void: Used for functions that execute successfully but do not return a value (or returnundefined).never: Represents a state that should never happen. It is used for functions that never finish executing (like an infinite loop) or functions that always throw an error.
function logMessage(msg: string): void {
console.log(msg); // Returns nothing
}
function throwError(msg: string): never {
throw new Error(msg); // Never reaches the end of the function
}
8. What are Enums in TypeScript?
Enums (Enumerations) allow you to define a set of named constants. They make it easier to document intent or create a set of distinct cases. TypeScript supports both numeric and string-based enums.
// Numeric Enum (Auto-increments from 0 by default)
enum Direction {
Up = 1,
Down, // 2
Left, // 3
Right // 4
}
// String Enum
enum LogLevel {
ERROR = "ERROR",
WARN = "WARN",
INFO = "INFO"
}
// Using the Numeric Enum
let playerMove: Direction = Direction.Up;
console.log(playerMove); // Output: 1
// Using the String Enum
let currentLevel: LogLevel = LogLevel.ERROR;
console.log(currentLevel); // Output: "ERROR"
9. What are Type Guards?
Type guards are techniques used to narrow down the type of a variable within a specific conditional block. TypeScript's compiler understands these checks and adjusts the type accordingly.
Common type guards include:
typeof(for primitive types)instanceof(for classes)in(to check for a property in an object)- Custom Type Predicates (
function isFish(pet: Fish | Bird): pet is Fish)
function process(input: string | number) {
if (typeof input === "string") {
return input.toUpperCase(); // TypeScript knows 'input' is a string here
}
return input.toFixed(2); // TypeScript knows 'input' is a number here
}
10. What is the ! (Non-null assertion) operator?
The non-null assertion operator (!) tells the TypeScript compiler that a value is definitely not null or undefined, even if the type checker thinks it might be. It bypasses strict null checks.
Warning: It should be used sparingly, as it can lead to runtime errors if the value actually is null.
let element = document.getElementById("my-app");
// element is inferred as HTMLElement | null
// We append '!' to tell TS we are 100% sure this element exists in the DOM
let app = document.getElementById("my-app")!;
app.style.color = "red";