Skip to content
Tutorials Center
My learning

Topics

Lesson 96 of 96 ยท Practice and Review

TypeScript Interview Questions

51 TypeScript interview questions with answers plus 5 code-reading puzzles: types, unions, narrowing, generics, utility, mapped and conditional types, TS 7.

TypeScript interviews test two things. First, whether you understand what the type system really does: that types vanish at runtime, that compatibility is structural, how narrowing follows your control flow, where any leaks in, and why some unsound rules exist on purpose. Second, whether you can apply it: model a domain with unions instead of flags, write a generic that keeps its types, validate data at the boundary, and choose a sensible tsconfig. This page collects 51 questions that come up again and again for frontend, Node.js and full-stack roles, grouped by level and topic, with short, accurate answers you can expand in your own words.

Try to answer each question out loud before you open it. If you can't explain an idea in two or three sentences, follow the link to its lesson. Five more questions ask you to read code and predict whether it compiles and what it prints: make your prediction first, then press Run. Our editor type-checks the program in strict mode before running it, exactly like tsc --strict followed by node.

Tip: strong answers name the trade-off, not just the feature. "unknown forces a check before use, so it's the right type for JSON.parse results and catch variables; any switches checking off and spreads silently." That sentence shows you know what each one is for. A tiny example and the compiler option involved (strictNullChecks, noUncheckedIndexedAccess) make it sound like experience.

Junior level

The basics

What is TypeScript, and why do teams use it?

TypeScript is JavaScript with a static type system. You add type annotations (or let the compiler infer types), the compiler checks that values are used consistently, and then it produces plain JavaScript. Teams use it because it catches whole classes of bugs before the code runs (typos in property names, missing null checks, wrong argument types), makes refactoring safe across large codebases, and powers editor features such as autocomplete, go-to-definition and rename. Every JavaScript program is close to valid TypeScript, so adoption can be gradual. See Getting Started with TypeScript.

What happens to types at runtime?

Nothing: they're erased. The compiler removes annotations, interfaces and type aliases, and the JavaScript that runs is just the code you wrote without them. That has consequences: you can't check if (x instanceof MyInterface), a User type doesn't validate data coming from an API, and a wrong type assertion never throws. When you need runtime checks, write them yourself (type guards) or use a schema library. The few TypeScript features that do produce code are enum, namespace with values, parameter properties and legacy decorators. See How TypeScript Works.

What is the difference between tsc and running a .ts file with Node.js?

tsc type-checks the whole program and, unless noEmit is set, writes JavaScript. Node.js (22.18+ and 24) can run .ts files directly through type stripping: it replaces the types with whitespace and runs the result, without checking them. Bundlers such as esbuild and Vite work the same way. So a common setup is: fast tools strip types during development and builds, and tsc --noEmit runs in the editor and in CI as the type checker. Type stripping only supports erasable syntax, which is why --erasableSyntaxOnly exists. See TypeScript with Node.js.

What is type inference? When should you write annotations?

Inference means the compiler works out a type from the code: let count = 0 is a number, a function's return type comes from its return statements, and a callback's parameters get their types from the function it's passed to (contextual typing). Annotate where inference can't help or where a contract matters: function parameters, exported functions and public APIs, and variables that start empty (const ids: number[] = []). Annotating every local variable adds noise and can widen types you wanted narrow. See Type Inference.

What is the difference between any and unknown?

Both accept every value. any also allows every operation on the value, so data.foo.bar() compiles and checking is effectively off; worse, any spreads into everything it touches. unknown allows no operations until you narrow it with typeof, instanceof, in, or a type guard. Use unknown for values you don't control yet: JSON.parse results, catch variables, untyped library output. In strict mode, catch (error) already gives unknown. See any, unknown, never and void.

What do void and never mean?

void is the return type of a function whose result shouldn't be used: it returns nothing (or undefined). never is the type with no values: the return type of a function that never returns normally (it always throws or loops forever), and the type of a variable after every possibility has been narrowed away. That second use powers exhaustiveness checks: const unreachable: never = value compiles only if every case was handled.

What does strictNullChecks change?

Without it, null and undefined are allowed in every type, so user.name.length compiles even when user may be missing, and the bug shows up at runtime. With it (part of strict), null and undefined are separate types: a value that might be absent has to be typed string | null or string | undefined, and the compiler forces a check (if, ?., ??) before use. It's the single most valuable strict option. See Strict Mode Explained.

Types and type aliases

What is the difference between an interface and a type alias?

Both can describe object shapes, and for most objects either works. interface supports extends and declaration merging (two declarations with the same name combine), which libraries use to let you add members, and error messages show its name. type can name anything: unions, tuples, functions, primitives, and computed types such as mapped and conditional types. A common convention: interface for object shapes that others may extend, type for unions and everything computed. See Interfaces and Type Aliases.

What is a union type, and how do you use a value of a union type?

A | B means "either an A or a B". You can only use members that exist on every part of the union directly; for anything else you narrow first. For string | number, value.toString() works right away, but value.toUpperCase() needs if (typeof value === 'string') first. Unions of literal types such as 'sm' | 'md' | 'lg' are the idiomatic way to express a fixed set of options. See Union Types.

What are literal types, and what does as const do?

A literal type is a single value used as a type: 'GET', 42, true. const method = 'GET' infers the literal type 'GET', while let method = 'GET' widens to string, because the variable could change. as const stops widening for a whole expression: object properties become readonly literals and arrays become readonly tuples. const SIZES = ['sm', 'md'] as const lets you derive type Size = (typeof SIZES)[number], one list for both runtime and types. See Literal Types and as const.

What is the difference between an array type and a tuple type?

number[] is a list of any length where every element is a number. A tuple such as [string, number] has a fixed length and a type per position, like the result of Object.entries or a useState-style pair. Tuples can have named, optional and rest elements: [name: string, age?: number], [string, ...number[]]. readonly number[] and readonly [x: number, y: number] forbid mutation. See Arrays and Tuples.

What is structural typing?

TypeScript compares types by their shape, not by their name or declaration. A value is assignable to Point if it has x and y of the right types, whether or not it was declared as a Point, and extra properties are fine. Classes are structural too: two classes with the same public members are interchangeable. The exception is object literals written directly where a type is expected: they get an excess property check, which catches typos like { nmae: 'Ada' }. When you need nominal behavior (a UserId that isn't just any string), use a branded type. See Type Compatibility and Variance.

Should you use enums or union types?

Both describe a fixed set of values. Enums are a TypeScript-only feature that generates runtime code: an object, with reverse mappings for numeric enums. Literal unions (type Status = 'active' | 'banned') generate nothing, read clearly in JSON and logs, and work with type stripping and --erasableSyntaxOnly, which reject enums. When you also need the values at runtime, use an as const object and derive the union from it. Enums are still fine in codebases that use them consistently, but many teams now prefer unions. See Enums.

What do as and the non-null assertion ! do? Are they safe?

value as T tells the compiler to treat a value as type T; value! removes null and undefined from its type. Neither does anything at runtime, so if you're wrong, the program fails later in a confusing place. TypeScript blocks obviously impossible assertions ('text' as number), but as unknown as T forces anything through, which is a code smell. Prefer narrowing, type guards or satisfies; keep assertions for cases where you know more than the compiler and can explain why. See Type Assertions and the Non-Null Operator.

What is the difference between an optional property and a property of type T | undefined?

email?: string means the property may be missing; email: string | undefined means it must be present but its value may be undefined. Reading either gives string | undefined. By default, the optional form also accepts an explicit undefined; with exactOptionalPropertyTypes it doesn't, which matters for code that checks 'email' in user or uses Object.keys. See Object Types.

Code reading: inference and excess properties

Predict whether this program compiles and, if so, what it prints.

TypeScript Predict the output: widening and excess properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Explanation

It compiles. unit has the literal type 'px', label widens to string (it's a let), point is { x: number; y: number } and sizes is (string | number)[], the "best common type" of its elements. At runtime typeof reports string string number, the map prints [ 20, 'auto' ], and ok still holds all three properties, because types don't change values. Assigning big to Size is allowed: it's a variable, not an object literal, so only structural compatibility is checked and the extra depth is fine. Writing const ok: Size = { width: 300, height: 200, depth: 50 } would fail with TS2353.

Mid level

Narrowing and functions

What is narrowing, and which constructs narrow a type?

Narrowing is the compiler following your control flow to give a variable a more specific type in each branch. It understands typeof x === 'string', x instanceof Date, 'prop' in x, equality (x === null, x === 'admin'), truthiness (if (x)), Array.isArray, assignments, early returns and throw, plus your own type predicates and assertion functions. It also works on discriminated unions by checking the tag property. Narrowing is lost when the compiler can't be sure the value didn't change, for example for mutable properties after a function call. See Narrowing.

What is a discriminated union, and why is it so useful?

A union of object types that share a literal "tag" property, such as { status: 'loading' } | { status: 'success'; data: User } | { status: 'error'; error: Error }. Checking the tag narrows to one member, so data is only accessible in the success branch. It replaces combinations of optional fields and booleans (isLoading, data?, error?) that allow impossible states. Add a default branch that assigns the value to never, and adding a new member becomes a compile error everywhere it isn't handled. See Discriminated Unions.

What is a user-defined type guard? What is an assertion function?

A type guard is a function returning a type predicate: function isUser(x: unknown): x is User. When it returns true, the argument is narrowed to User in that branch. An assertion function has the return type asserts x is User (or asserts condition): it returns normally only if the check passes and throws otherwise, so the code after the call is narrowed. The compiler trusts both, so their bodies must really check what they claim. Since TypeScript 5.5, simple arrow functions such as (x) => x !== null infer a predicate automatically, which is why filter can now remove nulls from an array's type. See Custom Type Guards.

When would you use function overloads instead of a union parameter?

When the return type depends on the argument type in a way a union can't express: parse(text: string): number and parse(texts: string[]): number[]. Callers see only the overload signatures and get the precise return type for each call. If the return type is the same for every input, a union parameter is simpler and better. Overloads are checked top to bottom, so put the most specific first; the implementation signature is not visible to callers. Generics with conditional types are an alternative for many cases. See Function Overloads.

Why can you pass a function with fewer parameters, or one that returns a value, where a void callback is expected?

Both rules match how JavaScript is used. Ignoring extra arguments is normal ([1, 2].map((n) => n * 2) ignores the index and array), so a function with fewer parameters is assignable to a type with more. And a callback type returning void means "the caller won't use the result", so forEach((n) => list.push(n)) is fine even though push returns a number. The void rule applies to function types; a function declaration annotated : void must not return a value. See Function Types and Callbacks.

How do you type this inside a function?

Declare a fake first parameter named this: function handle(this: Button, event: Event) {}. It's erased in the output and only tells the compiler what this is; calling the function with the wrong this is an error. With noImplicitThis (part of strict), using this where its type would be any is an error. Arrow functions capture this from their surroundings, which is why they're common for class callbacks. See this, Parameter Destructuring and Type Predicates.

Generics and type operators

What are generics, and what problem do they solve?

Generics are type parameters: placeholders that the caller (or inference) fills in. function first<T>(items: readonly T[]): T | undefined works for every element type and keeps it: first(['a']) returns string | undefined. Without generics you'd write one function per type or use any and lose the information. Classes and interfaces can be generic too (Map<K, V>, Promise<T>, your own Repository<T>). A good rule: a type parameter should appear at least twice, connecting an input to an output; otherwise you don't need it. See Generics.

What does T extends ... mean in a generic, and what is keyof?

<T extends { length: number }> is a constraint: callers may pass any type that has a numeric length, and inside the function you may use .length. keyof T is the union of T's property names, so <T, K extends keyof T>(obj: T, key: K): T[K] accepts only real keys and returns the matching property type (an indexed access type). Type parameters can also have defaults (<T = string>), and since 5.0 a const modifier (<const T>) that infers literal types as if the caller had written as const. See Generic Constraints and Defaults and keyof, typeof and Indexed Access Types.

Which utility types do you use most, and what do they do?

Partial<T> (all optional, for patches), Required<T>, Readonly<T> (shallow), Pick<T, K> and Omit<T, K> (keep or drop properties, for DTOs and props), Record<K, V> (an object with known keys), Exclude and Extract (filter unions), NonNullable<T>, ReturnType<F> and Parameters<F> (reuse a function's types), Awaited<T> (unwrap promises) and NoInfer<T> (5.4, stop a parameter from influencing inference). The point is deriving types from one source of truth instead of copying them. See Built-in Utility Types.

What does typeof mean inside a type?

In a type position, typeof value gives the type of a runtime value: type Config = typeof defaultConfig. It lets the value be the source of truth. Combined with keyof and indexed access, it derives unions from data: keyof typeof ROUTES gives the keys of an object, and (typeof ROLES)[number] gives the elements of an as const array. It's different from the runtime typeof operator, which returns a string such as 'object'.

What does satisfies do, and how is it different from an annotation or as?

value satisfies T checks that the value matches T but keeps the value's own, more precise inferred type. An annotation (const x: T = value) also checks, but then the variable is a T and precise information is lost: with Record<string, string | number>, every property becomes string | number. as T doesn't check compatibility in the same way and can hide mistakes. satisfies is ideal for configuration objects and lookup tables, often as as const satisfies T. See The satisfies Operator.

Classes and objects

What is the difference between private and #private?

TypeScript's private is checked only by the compiler: at runtime the property is ordinary and reachable with obj['secret'] or from JavaScript. #secret is a JavaScript private field: the engine enforces it, it doesn't show up in Object.keys or JSON.stringify, and it can't be reached from outside at all. Use # when privacy must hold at runtime (libraries); private is fine inside an application and allows subclass-free testing tricks. protected (subclasses only) has no JavaScript equivalent. See Access Modifiers and Private Fields.

When would you use an abstract class instead of an interface?

An interface is a pure contract with no code and no runtime existence. An abstract class can contain shared implementation, fields and constructors, plus abstract members that subclasses must implement; it exists at runtime, so instanceof works. Use an interface to describe what something can do (especially across unrelated classes, which can implement many interfaces); use an abstract class when subclasses share real behavior. A class can extend only one class. See Inheritance and Abstract Classes.

What does readonly guarantee?

readonly properties, Readonly<T> and readonly T[] make the compiler reject writes through that type. They're shallow (nested objects stay mutable unless you make them readonly too) and they're erased, so nothing stops a write at runtime, and a mutable alias of the same object can still change it. Object.freeze is the runtime counterpart, also shallow. Readonly types are still valuable: they document intent, and functions that take readonly arrays accept both mutable and readonly ones. See Readonly and Immutability.

What do index signatures and noUncheckedIndexedAccess do?

An index signature { [key: string]: number } describes an object with arbitrary keys. By default, reading scores['zoe'] is typed number even if the key doesn't exist, which is a classic source of undefined bugs. With noUncheckedIndexedAccess, every index access (also array[i]) includes | undefined, so you must check first. It's not part of strict, but many teams enable it. For known keys, a Record<'a' | 'b', number> or a Map is often the better type. See Index Signatures and Record.

Modules, declarations and errors

What is a .d.ts file, and where do @types packages come from?

A declaration file contains only types: signatures for functions, classes and values whose implementation lives in JavaScript. Libraries written in TypeScript ship .d.ts files generated by declaration: true. For JavaScript libraries, the community-maintained DefinitelyTyped project publishes them as @types/<package>, for example @types/node. You can write your own with declare module 'name' { ... }, and add to existing types with declaration merging and declare global. See Declaration Files.

What are import type and verbatimModuleSyntax?

import type { User } from './user.js' imports only a type and is removed completely from the output. With verbatimModuleSyntax, TypeScript requires that form for type-only imports and otherwise keeps imports exactly as written. That makes the output predictable for tools that compile one file at a time (esbuild, Node's type stripping), which can't know whether an imported name is a type. Inline form: import { save, type User } from './user.js'. See Modules.

How do you handle errors in a type-safe way?

In strict mode the catch variable is unknown (useUnknownInCatchVariables), because JavaScript can throw anything. Narrow with error instanceof Error (or your own error classes) before reading message. For expected failures, such as validation or "not found", many codebases return a Result type, { ok: true; value: T } | { ok: false; error: E }, which makes the failure part of the signature so callers can't forget it. Exceptions remain right for truly unexpected problems. Custom error classes should set name and can pass { cause } to keep the original error. See Error Handling.

How do you type async functions and Promise.all?

An async function always returns Promise<T>, so annotate it as async function load(): Promise<User>. await unwraps the promise, and Awaited<T> does the same at the type level. Promise.all([a, b]) with a tuple of different promises returns a typed tuple, so const [user, posts] = await Promise.all([loadUser(), loadPosts()]) gives each variable its own type. Promise.allSettled returns PromiseSettledResult<T>[], a discriminated union on status. See Promises and async/await.

Code reading: callbacks and narrowing

TypeScript Predict the output: void callbacks and fewer parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Explanation

It compiles and prints [ 30, 40 ] [ '#0', '#1', '#2', '#2' ] undefined. The first callback takes only one parameter, which is allowed for a two-parameter type, and it returns the number from push, which is allowed because the callback type returns void. The direct call logIndex(1, 2) adds a fourth entry and returns undefined; its type is void, so you couldn't do anything useful with result anyway.

TypeScript Predict whether it compiles: narrowing and closures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Explanation

It compiles and prints [ 5 ] [ 1, 2 ] [] and ANONYMOUS ADA. The first function narrows step by step: after the null check, the conditional gives string[] in both branches. The second is the interesting part. Inside the arrow function, name is still narrowed to string, because since TypeScript 5.4 narrowing is preserved in closures created after the last assignment to a let variable or parameter. In older versions this was error TS18048 ('name' is possibly 'undefined'), and it still is if you assign to name again after creating the closure.

Senior level

Type-level programming

What are conditional types, and what does distributive mean?

T extends U ? X : Y chooses a type based on assignability, and infer captures part of a matched type: T extends Promise<infer V> ? V : T. When T is a naked type parameter and receives a union, the conditional is applied to each member separately and the results are joined: ToArray<string | number> becomes string[] | number[]. That's how Exclude and Extract work. To treat the union as a whole, wrap both sides in a tuple: [T] extends [U]. Distribution also means never (the empty union) maps to never. See Conditional Types.

What are mapped types and key remapping?

A mapped type builds an object type by iterating over keys: { [K in keyof T]: T[K] }. Modifiers can be added or removed (readonly, ?, -readonly, -?), which is how Partial, Required and Readonly are implemented. Mapped types over keyof T are homomorphic: they preserve the original modifiers. Key remapping with as renames or filters keys: [K in keyof T as get${Capitalize<K & string>}] produces getter names, and remapping to never removes a key. See Mapped Types.

What can template literal types do, and where are their limits?

They build string literal types from other types: `on${Capitalize<E>}` turns 'click' | 'focus' into 'onClick' | 'onFocus', and `${number}px` matches strings like '12px'. With infer they can also parse: T extends `${infer Head}.${infer Rest}` splits a dotted path, which enables typed get(obj, 'a.b.c') helpers and route parameter extraction. The limits: unions multiply quickly (combining three 10-member unions gives 1,000 members), recursion has depth limits, and complex parsing types slow the compiler and produce unreadable errors. See Template Literal Types.

Explain covariance and contravariance with an example.

A generic type is covariant in T when Box<Dog> is assignable to Box<Animal> whenever Dog is assignable to Animal: that's safe for things you only read from. It's contravariant when the direction flips, which is the case for function parameters: a (a: Animal) => void can be used where a (d: Dog) => void is expected, but not the other way round, because the handler might receive a cat. With strictFunctionTypes, function-typed properties are checked contravariantly. Two deliberate holes remain: methods declared with method syntax are checked bivariantly, and arrays are covariant even though they're mutable. Since 4.7 you can annotate variance explicitly with in and out on type parameters. See Type Compatibility and Variance.

What is a branded type, and when do you need one?

Because typing is structural, a UserId defined as string is interchangeable with any other string, so passing an OrderId where a UserId belongs compiles. A brand adds a phantom property that no plain string has: type UserId = string & { readonly __brand: 'UserId' }. The only way to get one is through a function that validates and asserts (function toUserId(raw: string): UserId), so the type now proves that validation happened. Use brands for IDs, units (meters vs feet), and validated values such as emails or sanitized HTML. See Advanced Type-Level Programming.

When does advanced type-level code become a problem?

When types cost more than they save: error messages nobody can read, slow editor feedback, types only one person understands, and APIs that are hard to call. Signs include deep recursion, huge generated unions, many nested conditional types, and as any inside to make the types work. Good practice: keep complex types in a few well-tested utilities (tested with Expect<Equal<...>> checks), prefer simple overloads or plain unions at API boundaries, and measure with tsc --extendedDiagnostics when builds get slow.

What do const type parameters and NoInfer solve?

A const type parameter (5.0), function routes<const T extends readonly string[]>(paths: T), infers literal types as if the caller wrote as const, so routes(['/a', '/b']) gives readonly ['/a', '/b'] instead of string[]. NoInfer<T> (5.4) marks a position that shouldn't participate in inference. In function pick<C extends string>(options: C[], fallback: NoInfer<C>), C is inferred only from options, so a fallback that isn't one of the options is an error instead of silently widening C. See Generic Constraints and Defaults.

Code reading: distribution and array variance

TypeScript Predict the types: distributive conditionals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Explanation

It compiles. Wrap distributes over the union, so each member is wrapped separately. WrapWhole wraps the type parameter in a one-element tuple, which stops distribution, so the union stays together. IsString<'x' | 42> evaluates each member and joins the answers into 'yes' | 'no'. And IsString<never> is never, not 'no': never is an empty union, and distributing over zero members produces nothing. Write [T] extends [string] if you want never to give 'no'.

TypeScript Predict the output: arrays are covariant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Explanation

It compiles, and then the second iteration fails at runtime with dog.bark is not a function. Arrays are covariant in TypeScript: a Dog[] is assignable to Animal[], which is convenient for reading but unsound for writing, because push through the Animal[] alias puts a cat into the dogs' array. The compiler accepts this on purpose, since forbidding it would break a lot of ordinary code. The fix is to accept readonly Animal[] in functions that only read: a readonly array has no push, so covariance is safe.

Tooling, configuration and the ecosystem

What is TypeScript 7, and what changed?

TypeScript 7 is the native port of the compiler and language service to Go. The language and type-checking behavior are the same as in 5.x and 6.0, but builds and editor responses are roughly ten times faster, thanks to native code and parallel checking. TypeScript 6.0 was the bridge release: it deprecated old options (target: es5, moduleResolution: node10/classic, outFile, baseUrl and others) and changed some defaults; 7.0 removes them. Tools that drove the old JavaScript compiler API in-process have to adapt to the new one. See What's New in TypeScript 5.x, 6.0 and 7.0.

What does erasableSyntaxOnly do, and why does it matter now?

--erasableSyntaxOnly (5.8) reports an error for TypeScript features that generate runtime code instead of just being deleted: enums, namespaces with values, parameter properties (constructor(private x: number)), and import x = require(). Code that passes can be run by tools that only strip types, such as Node.js's built-in TypeScript support, with no transformation step. It pushes code toward plain JavaScript plus annotations, using unions instead of enums and explicit fields instead of parameter properties.

Which tsconfig options do you turn on for a new project, and why?

strict: true always. Then noUncheckedIndexedAccess (index access includes undefined), exactOptionalPropertyTypes (missing vs undefined), noImplicitOverride, verbatimModuleSyntax (predictable imports for single-file tools), skipLibCheck (faster; don't check dependencies' .d.ts files), and isolatedModules or erasableSyntaxOnly when a bundler or Node strips the types. module/moduleResolution depend on the runtime: nodenext for Node.js packages, bundler (with module: esnext or preserve) for apps built with Vite or similar. Libraries also need declaration: true and a correct exports map. See The tsconfig.json File.

How do you validate data from an API if types are erased?

Treat everything that crosses a boundary (HTTP responses, JSON.parse, localStorage, environment variables, user input) as unknown, and validate it at runtime before giving it a type. Small cases can use hand-written type guards. For real schemas, a validation library such as Zod or Valibot defines the schema once and infers the TypeScript type from it (type User = z.infer<typeof UserSchema>), so the check and the type can't drift apart. A plain as User on a response is a promise you can't keep. See Typing APIs and JSON Data.

How would you migrate a large JavaScript codebase to TypeScript?

Incrementally. Add a tsconfig.json with allowJs (and optionally checkJs with JSDoc types) so both languages build together; install @types packages; convert files leaf-first (utilities before the code that imports them) or by feature; start with strict off if necessary, then enable strict options one at a time, fixing errors per directory. Use // @ts-expect-error with a comment for known issues (it fails once the issue is fixed, unlike @ts-ignore), and forbid new any with lint rules. Track the number of remaining errors and suppressions as a metric. See Migrating JavaScript to TypeScript.

How does any leak into a codebase, and how do you stop it?

Common sources: JSON.parse, response.json() in older type definitions, untyped libraries, catch variables without strict mode, empty arrays and parameters without annotations (noImplicitAny catches those), and as any workarounds. Once a value is any, everything derived from it is any too, silently. Stop it with strict, return unknown from your own wrappers around these sources, validate at the boundary, and enable typescript-eslint rules such as no-explicit-any and the no-unsafe-* family, which flag uses of any values. See Best Practices and Common Mistakes.

What are declaration merging and module augmentation used for?

Interfaces with the same name merge, and so do a namespace and a function, class or enum of the same name. Module augmentation applies that to someone else's module: declare module 'express' { interface Request { user?: User } } adds a property to Express's request type everywhere. declare global { interface Window { analytics: Analytics } } does the same for globals (in a file that is a module). It's how frameworks let you type plugins and configuration. Use it sparingly, because it changes types globally. See Declaration Files and Namespaces.

What is the difference between standard decorators and experimentalDecorators?

TypeScript 5.0 implemented the standard TC39 decorators: a decorator is a function that receives the decorated value and a context object (ClassMethodDecoratorContext and so on) and can return a replacement, with accessor fields for decorating properties. The older experimentalDecorators follow an earlier proposal with a different signature and support parameter decorators and emitDecoratorMetadata, which Angular and NestJS rely on for dependency injection. They are not compatible with each other; new code without such a framework should use standard decorators. See Decorators.

What are using declarations?

using resource = getResource() (5.2, explicit resource management) calls resource[Symbol.dispose]() automatically when the enclosing block ends, whether it finishes normally, returns early or throws, like a finally you can't forget. await using does the same with Symbol.asyncDispose for async cleanup. Resources implement the Disposable or AsyncDisposable interfaces, and DisposableStack collects several. Typical uses: file handles, database connections, locks, temporary directories and timers in tests. See using Declarations and Explicit Resource Management.

How do you keep type checking fast in a large monorepo?

TypeScript 7's native compiler already makes checking several times faster. Beyond that: use project references (composite: true, tsc --build) so packages are checked separately and incrementally; enable incremental; set skipLibCheck; avoid giant unions and deeply recursive types in hot paths; add explicit return types on exported functions (cheaper declaration emit and clearer errors); and use isolatedDeclarations if you want tools to generate .d.ts files without full type checking. Measure with --extendedDiagnostics and --generateTrace before optimizing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of x in let x = 'GET';?

    let variables widen literal initializers to their general type because they can be reassigned. const x = 'GET' would have the literal type 'GET'.
  2. 2. Which statement about unknown is correct?

    unknown is the safe top type. Unlike any, it forces a typeof, instanceof or type guard check before you can use the value.
  3. 3. Does const animals: Animal[] = dogs; (with dogs: Dog[]) compile, and is it fully safe?

    Arrays are covariant for convenience. Writing through the wider alias can put wrong values into the original array; use readonly Animal[] for read-only parameters.
  4. 4. What is IsString<never> with type IsString<T> = T extends string ? 'yes' : 'no';?

    never is the empty union, and a distributive conditional over zero members produces never. Wrap the parameter as [T] extends [string] to get 'no'.
  5. 5. What does Node.js do with types when it runs a .ts file directly?

    Node's type stripping removes erasable type syntax and runs the JavaScript. Only tsc (or the TypeScript language service) actually type-checks.

Summary

  • Junior questions check the foundations: what TypeScript adds to JavaScript, type erasure, tsc vs type stripping, inference, any vs unknown, void and never, strictNullChecks, interfaces vs type aliases, unions and literal types, tuples, structural typing, enums vs unions, and the risks of as and !.
  • Mid-level questions focus on using the type system: narrowing and discriminated unions, type guards and assertion functions, overloads, callback assignability, generics with constraints and keyof, utility types, typeof in types, satisfies, private vs #private, readonly, index access, declaration files, import type, error handling and async types.
  • Senior questions dig into type-level programming (conditional, mapped and template literal types, variance, branded types, const parameters and NoInfer) and into engineering: TypeScript 7, erasableSyntaxOnly, tsconfig choices, runtime validation, migrations, stopping any, augmentation, decorators, using and build performance.
  • In every answer, a precise explanation, a tiny example, the trap and the compiler option or tool that catches it are what interviewers reward.

You've reached the end of the TypeScript course. Keep practicing with the exercises and the 40 classic programs, keep the cheat sheet close, and come back to the TypeScript course overview whenever you want to review a topic. Happy typing!