Typescript Interviews – Top Questions & Answers for Web Developers
TypeScript is a superset of JavaScript that adds static typing. It helps catch errors during development instead of runtime.
- Detects bugs early with type checking.
- Improves code readability and maintainability.
- Supports modern JS features (compiled to older JS versions).
- Great tooling (IntelliSense, autocompletion).
npm install -g typescriptThen compile a file:
tsc file.ts.ts for regular files and .tsx for files using JSX (React).
The TypeScript compiler (tsc) translates TypeScript to JavaScript, ensuring type safety and compatibility.
A type defines the shape of data — what kind of value (string, number, boolean, etc.) can be assigned to a variable.
string, number, boolean, null, undefined, bigint, and symbol.
TypeScript automatically infers the type when you declare and assign a variable:
let count = 10; // inferred as numberlet username: string = "John";
let age: number = 25;anydisables all type checking.unknownis safer — you must check the type before using it.
let value: unknown = "Hi";
if (typeof value === "string") console.log(value.toUpperCase());Interfaces define the structure or shape of an object.
interface User {
name: string;
age: number;
}interfaceis extendable and used for object shapes.typecan represent unions, primitives, and more.
type Status = "active" | "inactive";A variable can hold multiple types.
let result: string | number;It combines multiple types into one.
type A = { name: string };
type B = { age: number };
type C = A & B; // { name, age }Generics make components reusable with different data types.
function identity<T>(value: T): T {
return value;
}It gives a name to a type.
type ID = string | number;Enums are named constants.
enum Role { Admin, User, Guest }Tuples are fixed-length arrays with defined types.
let person: [string, number] = ["John", 30];It makes a property immutable.
interface User {
readonly id: number;
name: string;
}Use ? after the property name.
interface User {
name: string;
age?: number;
}It tells the compiler “trust me, I know the type.”
let input = document.getElementById("id") as HTMLInputElement;interfacedefines a structure.classdefines a blueprint with behavior (methods).
Used for functions that never return, like errors or infinite loops.
function throwError(): never {
throw new Error("Error!");
}Represents functions that don’t return anything.
function greet(): void {
console.log("Hello");
}They narrow down types at runtime.
function print(val: string | number) {
if (typeof val === "string") console.log(val.toUpperCase());
}Modules are files that export or import code to keep it organized.
export const a = 10;
import { a } from "./file";Namespaces group code logically in the same file (used less now).
namespace Utils {
export function log(msg: string) {
console.log(msg);
}
}The configuration file for the TypeScript compiler — defines rules, target versions, etc.
Decorators are functions that modify classes or methods (used in Angular).
function Logger(constructor: Function) {
console.log("Logging...");
}
@Logger
class User {}Used to declare variables or modules that exist elsewhere (e.g., JS libraries).
declare let $: any;Used to create new types based on existing ones.
type ReadonlyUser = {
readonly [K in keyof User]: User[K];
};Makes all properties optional.
type PartialUser = Partial<User>;Selects specific properties from a type.
type NameOnly = Pick<User, "name">;Removes properties from a type.
type UserWithoutAge = Omit<User, "age">;Creates a type with specific keys and values.
type Roles = Record<string, boolean>;Gets all property names of a type.
type Keys = keyof User; // "name" | "age"Gets the type of a variable or function.
const user = { name: "Tom" };
type UserType = typeof user;Used when you don’t know property names.
interface Dictionary {
[key: string]: string;
}Pre-built generic helpers like Partial, Pick, Omit, Record, Readonly, etc.
TypeScript checks structure compatibility, not exact matches.
interface Dog { name: string; }
let cat = { name: "Kitty" };
let dog: Dog = cat; // ✅ WorksInterfaces can merge automatically, but types cannot.
Through .tsx files and JSX typing — enhances props, states, and component type safety.
Used to type the context of a function.
function say(this: Person) {
console.log(this.name);
}function createUser() {
return { name: "Sam", age: 30 };
}
type User = ReturnType<typeof createUser>;Checks if a property exists in an object (also used in mapped types).
Union types with a common property for easy narrowing.
type Shape = { kind: "circle"; radius: number } | { kind: "square"; side: number };Use readonly or Readonly<T>.
Use [key: string]: any; or generics with keyof.
Limits the allowed types in generics.
function print<T extends string>(val: T) {
console.log(val);
}- Interface = structure.
- Abstract class = structure + shared logic.
The process of refining a union type to a specific one via checks.
Used for declaring external library types with .d.ts files.
JavaScript XML — used in React to describe UI elements.
Files containing type definitions for JavaScript libraries.
Enables all strict type checking options for safer code.
const enum inlines values during compilation, improving performance.
type Conditional<T> = T extends string ? string : number;Removes certain types from a union.
type Result = Exclude<"a" | "b" | "c", "a">; // "b" | "c"Selects certain types from a union.
type Result = Extract<"a" | "b" | "c", "a">; // "a"Removes null and undefined from a type.
Unwraps the result of a Promise.
type Add = (a: number, b: number) => number;function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
return a + b;
}const arr: readonly number[] = [1, 2];type OptionalTuple = [string, number?];Same as JS: == checks value, === checks value + type.
By compiling down to Promise-based JavaScript code.
Used for defining metadata (e.g., @Component, @Injectable).
Predefined helper types like Pick, Omit, Partial, etc.
If one type fits the structure of another, they are compatible.
Use interfaces or types to define the JSON structure.
Makes an object’s properties immutable and literal.
const config = { mode: "dark" } as const;function useValue<T = string>(val: T): T {
return val;
}namespace: internal module (same file).module: external (ES6 import/export).
Multiple interface declarations with the same name merge.
type UserName = User["name"];Technique to combine multiple classes together.
Enable strictNullChecks and handle null values properly.
interfaceextends→ inheritance.genericextends→ constraint.
Type logic that behaves like if-else.
type Check<T> = T extends string ? "String" : "Other";Used to extract types within conditional types.
type Return<T> = T extends (...args: any) => infer R ? R : never;Interfaces can’t handle unions easily, but types can.
A safer version of any that forces type checking before use.
- Static = belongs to the class.
- Instance = belongs to the object.
Use readonly or freeze the array.
Create interfaces representing API response structure.
Use ts-node or compile .ts files to .js before running.
They define reusable prop types for components.
Collection of type-safety features (noImplicitAny, strictNullChecks, etc.)
It compiles to older JavaScript versions based on target in tsconfig.
class User {
private id: number;
protected name: string;
}Public members are accessible anywhere.
interface Person { name: string; }
class User implements Person {
constructor(public name: string) {}
}Namespaces declared using declare namespace for external libraries.
Ensures an object matches a specific type but keeps literal inference.
const user = { name: "Tom" } satisfies User;object: any non-primitive.{}: literally any value exceptnull/undefined.
Extending an existing module with additional features.
Install @types/library or declare manually.
function greet(name: string) {}
type GreetType = typeof greet;Fewer runtime bugs
Predictable and readable code
Better tooling
Easier refactoring
Ideal for large-scale applications