[{"data":1,"prerenderedAt":602},["ShallowReactive",2],{"all-questions-typescript":3},{"beginner":4,"intermediate":210,"advanced":399},[5,15,22,29,38,49,57,65,73,81,88,97,105,115,124,132,142,152,163,173,183,194,202],{"id":6,"category":7,"question":8,"answer":9,"level":10,"tags":11},1,"TypeScript Basics","What is TypeScript and why is it used?","**Concept Explanation:** TypeScript is a strongly typed superset of JavaScript that compiles to plain JavaScript. It adds static types, classes, interfaces, and other features to enable better tooling and catch errors at compile time rather than runtime. TypeScript is used to improve code quality, maintainability, and developer experience, especially in large-scale applications.\n\n**Internal Behavior:** TypeScript code is transpiled to JavaScript by the TypeScript compiler (tsc). The compiler parses TypeScript into an Abstract Syntax Tree (AST), performs type checking based on annotations and inference, and then emits JavaScript code. Types are erased during compilation, so there is no runtime overhead.\n\n**Syntax & Code Example:**\n```ts\nfunction greet(name: string): string {\n  return `Hello, ${name}!`;\n}\n\nlet message: string = greet('World');\n```\n\n**Practical Example:** A large e-commerce platform uses TypeScript to define product, user, and order types. Developers get autocompletion and type checking, preventing bugs like passing a product ID where a user ID is expected.\n\n**Common Mistakes:** Assuming TypeScript will catch all runtime errors (it only catches type-related errors). Not enabling `strict` mode, missing many checks.\n\n**Edge Cases:** TypeScript cannot check dynamic properties added at runtime unless you use type assertions or index signatures.\n\n**Interview Follow-ups:** \"What is the difference between TypeScript and JavaScript?\" \"Can you use TypeScript with existing JS projects?\"\n\n**Best Practices:** Always enable `strict` mode. Use TypeScript for any project with more than a few files. Write `.d.ts` files for library integration.\n\n**Performance Considerations:** TypeScript only adds compilation time, not runtime performance. Use `tsc --noEmit` in CI for type checking without emitting.\n\n**Production Recommendations:** Compile TypeScript to JavaScript before deployment. Use `esbuild` or `swc` for faster transpilation.\n\n**Latest TypeScript Patterns:** Using `satisfies` operator (TS 4.9) for better type inference. `using` declarations (TS 5.2) for explicit resource management.\n\n**Interview Tip:** Emphasize that TypeScript is a tool for developer productivity and error prevention, not a runtime language. It's widely adopted in large codebases.\n\n**Common Follow-up:** \"What are the disadvantages of TypeScript?\" (Learning curve, build step, verbosity)\n\n**Real-world Example:** Google migrated its internal JavaScript codebase to TypeScript, resulting in a 50% reduction in bugs reported for those components.","beginner",[12,13,14],"typescript","basics","why-ts",{"id":16,"category":7,"question":17,"answer":18,"level":10,"tags":19},2,"What are the key benefits of using TypeScript over JavaScript?","**Concept Explanation:** TypeScript provides static type checking, which catches errors during development before runtime. It offers enhanced IDE support with autocompletion, refactoring tools, and navigation. TypeScript also supports modern JavaScript features (ES6+), compiling them to older versions for broader compatibility, and enables better code documentation through explicit types.\n\n**Internal Behavior:** TypeScript's type checker analyzes the codebase and reports type mismatches, unreachable code, and other issues. The language service powers IDE features like jump-to-definition, find-all-references, and rename-symbol across files.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F JavaScript - runtime error\nfunction add(a, b) {\n  return a + b;\n}\nadd('1', 2); \u002F\u002F Returns '12' silently\n\n\u002F\u002F TypeScript - compile-time error\nfunction add(a: number, b: number): number {\n  return a + b;\n}\nadd('1', 2); \u002F\u002F Error: Argument of type 'string' is not assignable to parameter of type 'number'\n```\n\n**Practical Example:** A team working on a financial app defines a `Currency` type. TypeScript prevents accidentally adding a number to a currency string, avoiding currency formatting bugs.\n\n**Common Mistakes:** Believing TypeScript guarantees bug-free code (it doesn't catch logic errors). Using `any` excessively, defeating type safety.\n\n**Edge Cases:** TypeScript cannot prevent all runtime errors, such as accessing undefined properties on objects that are typed as optional but not checked.\n\n**Interview Follow-ups:** \"Does TypeScript improve performance?\" \"How does TypeScript help with team collaboration?\"\n\n**Best Practices:** Use TypeScript in strict mode. Leverage advanced types like unions and generics. Document complex types with JSDoc comments.\n\n**Performance Considerations:** Compilation time increases with codebase size; use incremental builds and project references to speed up.\n\n**Production Recommendations:** Use `tsc --noEmit` in CI to type-check without emitting files. Use `skipLibCheck` for faster builds.\n\n**Latest TypeScript Patterns:** Using `module: 'NodeNext'` for ESM\u002FCJS interop. `verbatimModuleSyntax` for cleaner imports.\n\n**Interview Tip:** Mention that TypeScript's main benefit is catching type-related bugs early, which can save hours of debugging. Also highlight that TypeScript is not a runtime; it's a development tool.\n\n**Common Follow-up:** \"Can TypeScript catch all type errors?\"\n\n**Real-world Example:** Airbnb reported that 38% of their bugs were prevented by TypeScript after migrating 25% of their codebase.",[12,20,21],"benefits","vs-javascript",{"id":23,"category":7,"question":24,"answer":25,"level":10,"tags":26},3,"What is the difference between TypeScript and JavaScript?","**Concept Explanation:** TypeScript is a superset of JavaScript, meaning all valid JavaScript code is also valid TypeScript (with some configuration). The key differences are static typing, interfaces, generics, enums, and other compile-time features that JavaScript lacks. TypeScript code is transpiled to JavaScript for execution. JavaScript is dynamically typed and runs directly in browsers or Node.js.\n\n**Internal Behavior:** TypeScript adds a type system layer on top of JavaScript. The compiler performs type checking and then strips types, producing plain JavaScript. JavaScript engines don't understand TypeScript types.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F JavaScript\nlet x = 10;\nx = 'hello'; \u002F\u002F No error\n\n\u002F\u002F TypeScript\nlet x: number = 10;\nx = 'hello'; \u002F\u002F Error: Type 'string' is not assignable to type 'number'\n```\n\n**Practical Example:** In a JavaScript project, a function expecting a number can receive a string, causing runtime issues. In TypeScript, the error is caught at compile time.\n\n**Common Mistakes:** Thinking TypeScript is a different language (it's JavaScript + types). Assuming TypeScript code runs directly (needs compilation).\n\n**Edge Cases:** TypeScript can be configured to accept JavaScript files (`allowJs`). You can mix TS and JS during migration.\n\n**Interview Follow-ups:** \"What does 'superset' mean?\" \"Can you use TypeScript with existing JavaScript libraries?\"\n\n**Best Practices:** Gradually introduce TypeScript into JS projects using `allowJs` and `checkJs`. Use `@ts-check` in JS files before full migration.\n\n**Performance Considerations:** TypeScript compilation adds build time but no runtime overhead.\n\n**Production Recommendations:** Use TypeScript for new projects. For existing large JS projects, migrate incrementally.\n\n**Latest TypeScript Patterns:** TypeScript now supports many ECMAScript features before they're finalized (e.g., decorators, class fields).\n\n**Interview Tip:** Clarify that TypeScript is not a compiled language like C++; it's transpiled to JavaScript. The term 'compiled' is often used loosely for TypeScript.\n\n**Common Follow-up:** \"What JavaScript features are not supported in TypeScript?\"\n\n**Real-world Example:** Slack migrated their desktop app codebase from JavaScript to TypeScript, reducing bugs and improving developer productivity.",[12,27,28],"javascript","comparison",{"id":30,"category":31,"question":32,"answer":33,"level":10,"tags":34},4,"Types","What are type annotations in TypeScript?","**Concept Explanation:** Type annotations are explicit declarations of the expected type for variables, function parameters, return values, and other constructs. They tell TypeScript what type a value should have. While TypeScript can infer types, annotations provide clarity, enforce constraints, and serve as documentation.\n\n**Internal Behavior:** The TypeScript compiler uses annotations to check assignments and usages. If a value doesn't match its annotation, the compiler reports an error. Annotations are removed during compilation, so they don't affect runtime.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Variable annotation\nlet age: number = 30;\n\n\u002F\u002F Function parameter and return annotation\nfunction multiply(a: number, b: number): number {\n  return a * b;\n}\n\n\u002F\u002F Array annotation\nlet names: string[] = ['Alice', 'Bob'];\n\n\u002F\u002F Object annotation\nlet user: { name: string; age: number } = { name: 'John', age: 25 };\n```\n\n**Practical Example:** In a payment processing function, annotate parameters to ensure currency amounts are numbers, not strings, preventing calculation errors.\n\n**Common Mistakes:** Over-annotating when type inference is sufficient (reduces readability). Under-annotating, causing `any` inference.\n\n**Edge Cases:** Type annotations are not required for simple initializations (`let count = 5` infers `number`). For empty arrays, annotation is needed (`let arr: number[] = []`).\n\n**Interview Follow-ups:** \"When should you use type annotations vs inference?\" \"What happens if you annotate a variable with a different type than its initial value?\"\n\n**Best Practices:** Use annotations for function parameters and returns (public APIs). Use inference for simple local variables. Annotate when initialization is ambiguous.\n\n**Performance Considerations:** No runtime impact; annotations are erased.\n\n**Production Recommendations:** Use ESLint rule `no-inferrable-types` to avoid unnecessary annotations for simple literals.\n\n**Latest TypeScript Patterns:** Using `as const` for literal types. `satisfies` operator for type checking without widening.\n\n**Interview Tip:** Emphasize that TypeScript prefers inference but annotations are essential for function boundaries and when inference fails.\n\n**Common Follow-up:** \"Can you have type annotations for destructured parameters?\"\n\n**Real-world Example:** In a large codebase, a function `calculateTax(amount, rate)` lacked annotations, and a developer passed `amount` as a string, causing NaN. Adding `amount: number` prevented this bug.",[35,36,37],"type-annotations","syntax","types",{"id":39,"category":31,"question":40,"answer":41,"level":10,"tags":42},5,"What are primitive types in TypeScript?","**Concept Explanation:** Primitive types in TypeScript represent the basic data types in JavaScript: `string`, `number`, `boolean`, `symbol`, `bigint`, `null`, and `undefined`. TypeScript also includes `void` (absence of value, typically for functions returning nothing) and `never` (values that never occur).\n\n**Internal Behavior:** These types map directly to JavaScript primitives. The TypeScript compiler checks that operations on these types are valid (e.g., calling `toUpperCase()` on a number is invalid).\n\n**Syntax & Code Example:**\n```ts\nlet name: string = 'Alice';\nlet age: number = 30;\nlet isActive: boolean = true;\nlet userId: symbol = Symbol('id');\nlet bigNumber: bigint = 9007199254740991n;\nlet nullable: null = null;\nlet notDefined: undefined = undefined;\n\nfunction log(message: string): void {\n  console.log(message);\n}\n\nfunction throwError(): never {\n  throw new Error('Always throws');\n}\n```\n\n**Practical Example:** A user registration form: `name: string`, `age: number`, `isSubscribed: boolean`. TypeScript ensures age is not submitted as text.\n\n**Common Mistakes:** Using `Number` (object wrapper) instead of `number` primitive. Confusing `null` and `undefined` with `void`.\n\n**Edge Cases:** `void` differs from `undefined`: a `void` function can return `undefined`, but explicitly returning `null` is invalid.\n\n**Interview Follow-ups:** \"What is the difference between `null` and `undefined`?\" \"When would you use `never`?\"\n\n**Best Practices:** Use `number` not `Number`. Use `undefined` for missing optional values, `null` for intentional absence.\n\n**Performance Considerations:** No performance difference; they are runtime types.\n\n**Production Recommendations:** Enable `strictNullChecks` to catch `null`\u002F`undefined` errors.\n\n**Latest TypeScript Patterns:** Template literal types (`type Greeting = `Hello ${string}``) extend primitive string typing.\n\n**Interview Tip:** Clarify that `void` means a function returns nothing, while `never` means it never returns (infinite loop or throw).\n\n**Common Follow-up:** \"What is the difference between `void 0` and `undefined`?\"\n\n**Real-world Example:** In a Node.js API, a function `fetchUser(id: number): User | null` returns `null` if user not found. The caller must handle `null`, preventing `cannot read property of null` errors.",[43,44,45,46,47,48],"primitives","string","number","boolean","void","never",{"id":50,"category":31,"question":51,"answer":52,"level":10,"tags":53},6,"How do you define arrays and tuples in TypeScript?","**Concept Explanation:** Arrays in TypeScript are collections of elements of the same type. They can be defined using `type[]` or `Array\u003Ctype>`. Tuples are arrays with fixed length and specific types for each position. Tuples are useful for representing structured data like coordinate pairs or key-value pairs.\n\n**Internal Behavior:** TypeScript checks that all array elements match the specified type. For tuples, it checks both the length and the type of each element. At runtime, both are JavaScript arrays; the tuple constraints are only enforced at compile time.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Array syntax\nlet numbers: number[] = [1, 2, 3];\nlet strings: Array\u003Cstring> = ['a', 'b'];\n\n\u002F\u002F Tuple syntax\nlet person: [string, number] = ['Alice', 30];\nlet rgb: [number, number, number] = [255, 0, 128];\n\n\u002F\u002F Optional tuple elements\nlet optionalTuple: [string, number?] = ['Alice']; \u002F\u002F second element optional\n\n\u002F\u002F Rest elements in tuple\nlet header: [string, ...number[]] = ['first', 1, 2, 3];\n```\n\n**Practical Example:** A CSV parser returns rows as `[string, string, number]` for [name, email, age]. Using a tuple ensures type safety when accessing columns.\n\n**Common Mistakes:** Using a tuple where an array would suffice (over-constraining). Modifying tuple length via `push` (TypeScript allows it but may cause runtime issues).\n\n**Edge Cases:** Tuples with optional elements must be placed after required ones. `readonly` tuples prevent mutation: `const point: readonly [number, number] = [10, 20];`\n\n**Interview Follow-ups:** \"How do you create a tuple type for a CSV row?\" \"What is the difference between tuple and array?\"\n\n**Best Practices:** Use arrays for homogenous collections. Use tuples for fixed-size, mixed-type data. Prefer labeled tuples for readability: `[name: string, age: number]`.\n\n**Performance Considerations:** No runtime difference; both are JavaScript arrays.\n\n**Production Recommendations:** Use `readonly` tuples for immutable data. Use `as const` to infer literal tuple types.\n\n**Latest TypeScript Patterns:** Labeled tuple elements (TS 4.0+). Variadic tuple types (TS 4.0+).\n\n**Interview Tip:** Highlight that tuples are compile-time only; they don't enforce length at runtime unless you add checks.\n\n**Common Follow-up:** \"Can tuples have variable length?\" (Yes, using rest elements)\n\n**Real-world Example:** A function `useState` in React returns a tuple `[value, setter]`. TypeScript's tuple typing ensures you don't accidentally swap them.",[54,55,56],"arrays","tuples","collections",{"id":58,"category":31,"question":59,"answer":60,"level":10,"tags":61},7,"What are enums in TypeScript and how do they work?","**Concept Explanation:** Enums (enumerations) allow defining a set of named constants. They make code more readable and reduce magic numbers\u002Fstrings. TypeScript supports numeric enums (auto-incrementing values), string enums, and heterogeneous enums (mixed numeric and string).\n\n**Internal Behavior:** Numeric enums generate reverse mappings (value to name) and are compiled to objects. String enums do not have reverse mappings. Const enums (`const enum`) are inlined at usage sites and not emitted as objects.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Numeric enum\nenum Direction {\n  Up,    \u002F\u002F 0\n  Down,  \u002F\u002F 1\n  Left,  \u002F\u002F 2\n  Right  \u002F\u002F 3\n}\n\n\u002F\u002F Custom numeric values\nenum Status {\n  Pending = 1,\n  Approved = 2,\n  Rejected = 3\n}\n\n\u002F\u002F String enum\nenum Color {\n  Red = 'RED',\n  Green = 'GREEN',\n  Blue = 'BLUE'\n}\n\n\u002F\u002F Const enum (inlined)\nconst enum LogLevel {\n  Info,\n  Warn,\n  Error\n}\n\nlet dir: Direction = Direction.Up;\n```\n\n**Practical Example:** HTTP status codes as an enum: `enum HttpStatus { OK = 200, NotFound = 404 }`. Using `HttpStatus.OK` is clearer than `200`.\n\n**Common Mistakes:** Assuming numeric enums are type-safe for values (any number can be assigned to a numeric enum type). Overusing enums where union types would suffice.\n\n**Edge Cases:** String enums cannot have reverse mapping. `const enum` may cause errors if used with `isolatedModules`. Ambient enums (declared but not defined) have special behavior.\n\n**Interview Follow-ups:** \"What is the emitted JavaScript for a numeric enum?\" \"When should you use union types instead of enums?\"\n\n**Best Practices:** Prefer union types (`type Status = 'pending' | 'approved'`) for simple cases. Use enums when you need a closed set of related constants and want to avoid string duplication.\n\n**Performance Considerations:** Regular enums emit code; `const enum` has zero runtime overhead but cannot be used with `isolatedModules`.\n\n**Production Recommendations:** Use `const enum` for performance (if not using `isolatedModules`). Otherwise, use union types or regular enums.\n\n**Latest TypeScript Patterns:** `enum` member expressions can be computed. `enum` can be used with `as const` object alternatives.\n\n**Interview Tip:** Many developers overuse enums. Mention that union types are often simpler and integrate better with tooling.\n\n**Common Follow-up:** \"How do you iterate over enum keys?\"\n\n**Real-world Example:** In a game, `enum Weapon { Sword, Bow, Staff }` is used to switch on weapon type. Using enum prevents typos like 'Sowrd' that would be caught at compile time.",[62,63,64,44],"enums","constants","numeric",{"id":66,"category":31,"question":67,"answer":68,"level":10,"tags":69},8,"What is the 'any' type in TypeScript and when should you use it?","**Concept Explanation:** `any` is a special type that disables type checking for a value. A variable of type `any` can hold any type, and you can access any property or call any method without type errors. `any` effectively opts out of TypeScript's type system.\n\n**Internal Behavior:** The compiler treats `any` as fully dynamic. No type checks are performed on `any` values. This can mask bugs but is useful when migrating JavaScript code or dealing with truly dynamic data.\n\n**Syntax & Code Example:**\n```ts\nlet data: any = 'hello';\ndata = 42;           \u002F\u002F OK\ndata.toFixed();      \u002F\u002F OK (runtime error if data is string)\ndata.anything.goes(); \u002F\u002F No compile error\n\n\u002F\u002F Implicit any (if no annotation and inference fails)\nfunction process(input) { \u002F\u002F parameter 'input' implicitly has type 'any'\n  return input;\n}\n```\n\n**Practical Example:** When parsing JSON from an unreliable API, you might use `any` temporarily until you define proper types. However, better to use `unknown` and validate.\n\n**Common Mistakes:** Using `any` everywhere (defeats purpose of TypeScript). Using `any` instead of proper types like `unknown` or generics.\n\n**Edge Cases:** `any` is assignable to any type, and any type is assignable to `any`. This breaks type safety. The `noImplicitAny` compiler option prevents implicit any.\n\n**Interview Follow-ups:** \"What is the difference between `any` and `unknown`?\" \"When is it safe to use `any`?\"\n\n**Best Practices:** Avoid `any` as much as possible. Use `unknown` when you don't know the type but need type safety. Use `any` only during migration or for extremely dynamic data where you are certain of the operations.\n\n**Performance Considerations:** No performance impact; type checking is compile-time only.\n\n**Production Recommendations:** Enable `noImplicitAny` to catch accidental any. Use ESLint rule `@typescript-eslint\u002Fno-explicit-any` to ban any in production code.\n\n**Latest TypeScript Patterns:** Use `unknown` instead of `any` and use type guards to narrow. Use `satisfies` to infer types without widening.\n\n**Interview Tip:** Emphasize that `any` is a last resort. Modern TypeScript provides `unknown`, `never`, and generics to handle dynamic cases safely.\n\n**Common Follow-up:** \"Can you use `any` for function parameters?\"\n\n**Real-world Example:** A logging function that can accept any value: `function log(value: any) { console.log(value); }`. This is acceptable because it doesn't operate on the value's properties. But even here, `unknown` would be safer and require narrowing if you needed to inspect it.",[70,71,72],"any","dynamic","type-unsafe",{"id":74,"category":31,"question":75,"answer":76,"level":10,"tags":77},9,"What is the 'unknown' type and how does it differ from 'any'?","**Concept Explanation:** `unknown` is a type-safe counterpart to `any`. A variable of type `unknown` can hold any value, but before you can perform operations on it, you must narrow the type (using type guards, assertions, or checks). `unknown` forces you to verify the type, preventing accidental runtime errors.\n\n**Internal Behavior:** The compiler treats `unknown` as a top type (like `any`) but with restrictions. You cannot assign an `unknown` to a typed variable without narrowing, and you cannot access properties on it directly.\n\n**Syntax & Code Example:**\n```ts\nlet value: unknown = 'hello';\n\u002F\u002F value.toUpperCase(); \u002F\u002F Error: Object is of type 'unknown'\n\n\u002F\u002F Narrowing with typeof\nif (typeof value === 'string') {\n  value.toUpperCase(); \u002F\u002F OK\n}\n\n\u002F\u002F Type assertion (use with caution)\n(value as string).toUpperCase();\n\n\u002F\u002F Cannot assign unknown to specific type without check\nlet str: string = value; \u002F\u002F Error\n```\n\n**Practical Example:** A function that parses JSON: `JSON.parse` returns `any` by default, but you can type it as `unknown` and then validate the structure using a type guard or validation library like Zod.\n\n**Common Mistakes:** Treating `unknown` like `any` and not narrowing. Using type assertions to bypass checks, defeating safety.\n\n**Edge Cases:** `unknown` is not assignable to any type except `any` and `unknown` itself. However, every type is assignable to `unknown`.\n\n**Interview Follow-ups:** \"Why was `unknown` introduced?\" \"How do you safely narrow an unknown value?\"\n\n**Best Practices:** Use `unknown` for values from external sources (API responses, user input). Always validate before use. Use type guards, `instanceof`, or validation libraries.\n\n**Performance Considerations:** No runtime impact; type narrowing is compile-time.\n\n**Production Recommendations:** Prefer `unknown` over `any` for external data. Combine with Zod or io-ts for runtime validation.\n\n**Latest TypeScript Patterns:** Using `is` type guard functions to narrow `unknown` to specific types.\n\n**Interview Tip:** The key difference is that `unknown` forces you to handle the uncertainty, while `any` lets you pretend you know the type. `unknown` is therefore safer.\n\n**Common Follow-up:** \"Can `unknown` be used in union types?\"\n\n**Real-world Example:** An event handler that receives data from a WebSocket: `function handleEvent(data: unknown) { if (isValidMessage(data)) { process(data); } }`. This ensures malformed data doesn't crash the app.",[78,79,80],"unknown","type-safety","any-alternative",{"id":82,"category":31,"question":83,"answer":84,"level":10,"tags":85},10,"What are the 'void' and 'never' types in TypeScript?","**Concept Explanation:** `void` represents the absence of a return value from a function. It's used for functions that don't return anything (or return `undefined`). `never` represents values that never occur, such as functions that always throw an error or have infinite loops. `never` is also used for exhaustiveness checking.\n\n**Internal Behavior:** `void` functions can return `undefined` or no return statement. `never` functions never complete. TypeScript uses `never` in type narrowing (e.g., after a `type guard` that eliminates all possibilities).\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F void function\nfunction logMessage(message: string): void {\n  console.log(message);\n  \u002F\u002F implicit return undefined\n}\n\n\u002F\u002F never function\nfunction throwError(message: string): never {\n  throw new Error(message);\n}\n\nfunction infiniteLoop(): never {\n  while (true) {}\n}\n\n\u002F\u002F Exhaustiveness checking with never\ntype Shape = Circle | Square;\nfunction area(shape: Shape): number {\n  switch (shape.kind) {\n    case 'circle': return Math.PI * shape.radius ** 2;\n    case 'square': return shape.side ** 2;\n    default:\n      const _exhaustiveCheck: never = shape;\n      return _exhaustiveCheck;\n  }\n}\n```\n\n**Practical Example:** In a reducer function, the default case can assign to `never` to ensure all action types are handled.\n\n**Common Mistakes:** Using `void` as a type for variables (it can only hold `undefined`). Thinking `never` means the same as `void`.\n\n**Edge Cases:** `void` functions can return `undefined` explicitly. `void` is also used in callbacks where you don't care about the return value (`forEach`).\n\n**Interview Follow-ups:** \"What happens if a void function returns a value?\" \"Can a never function return?\"\n\n**Best Practices:** Use `void` for functions that do not return a meaningful value. Use `never` for unreachable code or exhaustive checks. Use `never` in conditional types to filter out cases.\n\n**Performance Considerations:** No runtime impact.\n\n**Production Recommendations:** Use exhaustiveness checking with `never` to catch unhandled cases in unions.\n\n**Latest TypeScript Patterns:** `never` is used in advanced mapped types to filter keys.\n\n**Interview Tip:** Emphasize that `never` is a bottom type (no values), while `void` is a unit type (only `undefined`). This distinction is important for type logic.\n\n**Common Follow-up:** \"Can a variable be of type `never`?\"\n\n**Real-world Example:** In a Redux reducer, the default case uses `never` to ensure all action types are covered: `default: const _exhaustiveCheck: never = action; throw new Error('Unhandled action');`",[47,48,86,87],"functions","exhaustiveness",{"id":89,"category":31,"question":90,"answer":91,"level":10,"tags":92},11,"How does TypeScript treat null and undefined?","**Concept Explanation:** In TypeScript, `null` and `undefined` are separate primitive types. By default (with `strictNullChecks` off), they are assignable to any type. With `strictNullChecks` enabled (recommended), they are only assignable to their own types and the `unknown` and `any` types. This prevents common runtime errors like accessing properties on `null`.\n\n**Internal Behavior:** The compiler uses control flow analysis to narrow `null` and `undefined`. For example, after checking `if (value !== null)`, TypeScript knows `value` is not null.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F With strictNullChecks: true\nlet value: string = 'hello';\nvalue = null; \u002F\u002F Error: Type 'null' is not assignable to type 'string'\n\nlet maybe: string | null = 'hello';\nmaybe = null; \u002F\u002F OK\n\n\u002F\u002F Optional parameters are automatically `undefined`\nfunction greet(name?: string) {\n  \u002F\u002F name is string | undefined\n  console.log(name?.toUpperCase()); \u002F\u002F Optional chaining\n}\n\n\u002F\u002F Non-null assertion (use sparingly)\nlet element = document.getElementById('app')!; \u002F\u002F Asserts not null\n```\n\n**Practical Example:** A function that finds a user by ID: `findUser(id: number): User | null`. The caller must handle `null` case, preventing crashes.\n\n**Common Mistakes:** Assuming a value is non-null after it could have been set to null. Overusing non-null assertions (`!`) instead of proper checks.\n\n**Edge Cases:** `undefined` is the default value for optional parameters and uninitialized properties. `null` is usually intentional absence. TypeScript's `--strictNullChecks` also affects optional chaining and nullish coalescing (`??`).\n\n**Interview Follow-ups:** \"What is the difference between `null` and `undefined`?\" \"How do you handle optional object properties?\"\n\n**Best Practices:** Enable `strictNullChecks`. Use union types with `null` or `undefined` for optional values. Use optional chaining (`?.`) and nullish coalescing (`??`) to handle null\u002Fundefined gracefully.\n\n**Performance Considerations:** No runtime impact; types are erased.\n\n**Production Recommendations:** Never disable `strictNullChecks` in production code. Use `exactOptionalPropertyTypes` for stricter optional property handling.\n\n**Latest TypeScript Patterns:** `exactOptionalPropertyTypes` distinguishes between optional and undefined. `throwIfNullable` patterns with `never`.\n\n**Interview Tip:** Emphasize that `strictNullChecks` is one of the most valuable TypeScript features, eliminating billions of `Cannot read property 'x' of null` errors.\n\n**Common Follow-up:** \"What is the non-null assertion operator and when is it safe?\"\n\n**Real-world Example:** A React component with `useRef\u003CHTMLDivElement>(null)`. You must check `ref.current` is not null before calling methods like `focus()`. TypeScript enforces this check, preventing runtime errors.",[93,94,95,96],"null","undefined","strictNullChecks","optional",{"id":98,"category":99,"question":100,"answer":101,"level":10,"tags":102},12,"Type Inference","How does type inference work in TypeScript?","**Concept Explanation:** Type inference is TypeScript's ability to automatically determine types when they are not explicitly annotated. The compiler analyzes initial values, return statements, and usage context to infer types. This reduces verbosity while maintaining safety.\n\n**Internal Behavior:** The compiler uses a process called 'contextual typing' and 'best common type' to infer types. For variables, it infers from the initializer. For functions, it infers return types from return statements. For complex expressions, it finds the most specific type that all members share.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Variable inference\nlet x = 5;      \u002F\u002F inferred as number\nlet y = 'hello'; \u002F\u002F inferred as string\nlet z = [1, 2]; \u002F\u002F inferred as number[]\n\n\u002F\u002F Function return inference\nfunction add(a: number, b: number) {\n  return a + b; \u002F\u002F inferred as number\n}\n\n\u002F\u002F Contextual typing\nwindow.onmousedown = function(mouseEvent) {\n  \u002F\u002F mouseEvent inferred as MouseEvent\n  console.log(mouseEvent.button);\n};\n\n\u002F\u002F Best common type\nlet items = [1, 'two', 3]; \u002F\u002F inferred as (string | number)[]\n```\n\n**Practical Example:** In a map function, TypeScript infers the array element type from the return expression: `[1,2,3].map(x => x * 2)` infers `number[]`.\n\n**Common Mistakes:** Relying on inference when initialization is ambiguous (e.g., empty array). Not annotating function return types for public APIs (can cause errors to propagate).\n\n**Edge Cases:** Best common type picks the most specific type that all elements can be assigned to. If no common type, it infers a union. With `noImplicitAny`, uninitialized variables or parameters without inference cause errors.\n\n**Interview Follow-ups:** \"When should you rely on inference vs explicit annotations?\" \"What is contextual typing?\"\n\n**Best Practices:** Annotate function return types for public APIs. Let inference handle simple local variables. Use explicit types for complex objects and arrays with mixed types.\n\n**Performance Considerations:** Inference is compile-time; no runtime cost.\n\n**Production Recommendations:** Use `noImplicitAny` to ensure inference doesn't accidentally produce `any`. Use `exactOptionalPropertyTypes` for stricter inference.\n\n**Latest TypeScript Patterns:** `satisfies` operator allows type inference while checking against a type. `as const` for literal inference.\n\n**Interview Tip:** Emphasize that inference is powerful but not magic. For critical boundaries (API, function signatures), explicit types are better documentation.\n\n**Common Follow-up:** \"Can TypeScript infer types from usage after declaration?\"\n\n**Real-world Example:** A developer wrote `let result;` without initialization, then `result = apiCall();`. TypeScript infers `any` (if `noImplicitAny` off) or error (if on). Adding `let result: ReturnType\u003Ctypeof apiCall>;` fixes it.",[103,37,104],"inference","automatic",{"id":106,"category":107,"question":108,"answer":109,"level":10,"tags":110},13,"Union & Literal Types","What are union types and literal types in TypeScript?","**Concept Explanation:** Union types allow a variable to hold values of multiple types, defined using the pipe symbol (`|`). Literal types are specific values (strings, numbers, booleans) that act as types. You can combine them to create narrow, precise types (e.g., `type Status = 'pending' | 'approved' | 'rejected'`).\n\n**Internal Behavior:** TypeScript uses control flow analysis to narrow union types based on checks (`typeof`, `instanceof`, custom guards). Literal types prevent assigning values outside the specified set.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Union type\nlet value: string | number = 'hello';\nvalue = 42; \u002F\u002F OK\nvalue = true; \u002F\u002F Error: boolean not allowed\n\n\u002F\u002F Literal types\nlet direction: 'up' | 'down' = 'up';\ndirection = 'left'; \u002F\u002F Error\n\n\u002F\u002F Union of literals (discriminated union)\ntype Status = 'pending' | 'approved' | 'rejected';\nlet requestStatus: Status = 'pending';\n\n\u002F\u002F Using with type guards\nfunction process(value: string | number) {\n  if (typeof value === 'string') {\n    return value.toUpperCase(); \u002F\u002F string\n  } else {\n    return value.toFixed(2);    \u002F\u002F number\n  }\n}\n```\n\n**Practical Example:** A form input can accept either a string or a File object: `type FormValue = string | File;`. Functions handle both cases.\n\n**Common Mistakes:** Using union types when intersection is needed. Forgetting to narrow before accessing type-specific properties. Overly broad unions causing many checks.\n\n**Edge Cases:** Union types with objects require narrowing. TypeScript's `in` operator or user-defined type guards can narrow object unions. Empty union (`never`) is useful for exhaustive checks.\n\n**Interview Follow-ups:** \"What is a discriminated union?\" \"How do you narrow union types?\"\n\n**Best Practices:** Use discriminated unions (common property `kind`) for object unions. Prefer literal unions over enums for simple cases. Use `const assertions` (`as const`) to derive literal types from objects.\n\n**Performance Considerations:** No runtime impact.\n\n**Production Recommendations:** Use literal unions for API response statuses, event types, and other closed sets. Combine with exhaustive checking using `never`.\n\n**Latest TypeScript Patterns:** Template literal types allow building literal types from strings. `satisfies` operator preserves literal types.\n\n**Interview Tip:** Emphasize that literal unions are often better than enums because they are simpler, have no runtime code, and work well with autocomplete.\n\n**Common Follow-up:** \"Can you compute union types from arrays?\" (Yes, using `as const` and `typeof`)\n\n**Real-world Example:** A React component with `size: 'small' | 'medium' | 'large'`. Using literal unions ensures only valid sizes are passed, preventing bugs like `size='big'`.",[111,112,113,114],"union","literal","narrowing","discriminated-union",{"id":116,"category":117,"question":118,"answer":119,"level":10,"tags":120},14,"Functions","How do you type functions, optional, default, and rest parameters in TypeScript?","**Concept Explanation:** TypeScript allows typing function parameters and return values. Parameters can be optional (with `?`), have default values, or use rest syntax (`...args`). Function types can also be defined separately.\n\n**Internal Behavior:** The compiler checks that callers pass correct types for parameters. Optional parameters must come after required ones. Default parameters also become optional. Rest parameters are collected into an array of the specified type.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Basic function typing\nfunction add(a: number, b: number): number {\n  return a + b;\n}\n\n\u002F\u002F Optional parameter\nfunction greet(name: string, greeting?: string): string {\n  return `${greeting || 'Hello'}, ${name}`;\n}\n\n\u002F\u002F Default parameter\nfunction multiply(a: number, b: number = 1): number {\n  return a * b;\n}\n\n\u002F\u002F Rest parameters\nfunction sum(...numbers: number[]): number {\n  return numbers.reduce((a, b) => a + b, 0);\n}\n\n\u002F\u002F Function type (signature)\ntype MathOperation = (a: number, b: number) => number;\nconst subtract: MathOperation = (x, y) => x - y;\n```\n\n**Practical Example:** A logging function: `function log(level: LogLevel, ...messages: unknown[]) { console[level](...messages); }`.\n\n**Common Mistakes:** Placing optional parameters before required ones (TS disallows). Forgetting that default parameters also become optional, so callers can omit them.\n\n**Edge Cases:** Optional parameters and default parameters cannot both be used on the same parameter (default implies optional). Rest parameters must be last.\n\n**Interview Follow-ups:** \"What is the difference between `?:` and `= defaultValue`?\" \"How do you type function overloads?\"\n\n**Best Practices:** Use default parameters instead of optional when you have a sensible default. Prefer arrow functions for callbacks to preserve `this`. Use function types (`type Fn = (x: number) => void`) for callbacks.\n\n**Performance Considerations:** No runtime impact.\n\n**Production Recommendations:** Use `void` return type for callbacks that don't need to return anything. Use `unknown` for rest parameters that can be any type.\n\n**Latest TypeScript Patterns:** Const type parameters (`\u003Cconst T>`) to infer literal types. Function overloads with rest parameters.\n\n**Interview Tip:** Emphasize that optional parameters and default parameters are compile-time features; at runtime, missing parameters become `undefined`.\n\n**Common Follow-up:** \"Can you mix optional and rest parameters?\"\n\n**Real-world Example:** An API client function `request(url: string, options?: RequestOptions)` has optional options. Default parameters provide common defaults like `method = 'GET'`. This makes the API flexible and easy to use.",[86,121,96,122,123],"parameters","default","rest",{"id":125,"category":126,"question":127,"answer":128,"level":10,"tags":129},15,"Interfaces & Types","What is the difference between interface and type alias in TypeScript?","**Concept Explanation:** Both `interface` and `type` can describe object shapes and function signatures. `interface` is specifically for objects and can be merged (declaration merging) and extended. `type` can represent primitives, unions, tuples, and more complex types. `type` cannot be re-opened (no declaration merging) and cannot implement classes.\n\n**Internal Behavior:** Interfaces are more optimized for object type caching and error messages. Types are more flexible but can't be merged. The compiler treats them similarly for most object types.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Interface\ninterface User {\n  name: string;\n  age: number;\n}\n\n\u002F\u002F Type alias\ntype Point = { x: number; y: number };\n\n\u002F\u002F Type alias for union (interface can't do)\ntype Status = 'active' | 'inactive';\n\n\u002F\u002F Interface extension (declaration merging)\ninterface User {\n  email: string; \u002F\u002F Adds to existing User\n}\n\n\u002F\u002F Type intersection\ntype Admin = User & { role: string };\n\n\u002F\u002F Interface extends\ntype Animal = { name: string };\ninterface Dog extends Animal { bark(): void; }\n```\n\n**Practical Example:** For a library API, use interfaces because they merge, allowing users to augment definitions. For union types, mapped types, or complex type manipulations, use types.\n\n**Common Mistakes:** Trying to extend a type alias that is not an object type. Using `implements` with a union type (only interfaces).\n\n**Edge Cases:** `type` can use `typeof` to capture variable types. `interface` cannot. `type` can be recursive, `interface` can also be recursive but with more restrictions.\n\n**Interview Follow-ups:** \"Which one is more performant?\" \"Can you implement a type alias in a class?\"\n\n**Best Practices:** Use `interface` for object shapes that are part of an API and may be extended. Use `type` for unions, tuples, primitives, and type transformations.\n\n**Performance Considerations:** Interfaces are slightly faster for type checking in large codebases because they are cached.\n\n**Production Recommendations:** Prefer interfaces for public APIs (declaration merging), types for internal domain-specific types.\n\n**Latest TypeScript Patterns:** `type` can use `as const` assertions, `interface` cannot. `interface` can extend from `type` if the type is an object.\n\n**Interview Tip:** Emphasize that both are powerful, but `interface` is more semantic for objects. Many large codebases use `interface` for objects and `type` for everything else.\n\n**Common Follow-up:** \"Can interface extend a type alias that is a union?\" (No)\n\n**Real-world Example:** In a library, `interface Options` allows users to add their own properties via declaration merging. If the library used `type`, that would not be possible.",[130,131,28],"interface","type-alias",{"id":133,"category":134,"question":135,"answer":136,"level":10,"tags":137},16,"Objects","How do you type objects in TypeScript? Explain index signatures and excess property checks.","**Concept Explanation:** Objects in TypeScript are typed by defining the shape of their properties. You can use interfaces or type aliases to describe property names and their types. Index signatures allow objects with dynamic property names. Excess property checks prevent passing extra properties directly to object literals.\n\n**Internal Behavior:** TypeScript checks object assignments for shape compatibility. If an object literal has properties not defined in the target type, TypeScript raises an error (excess property check). This check does not apply when assigning an object variable to another variable.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Basic object type\ninterface Person {\n  name: string;\n  age: number;\n}\n\nlet user: Person = { name: 'Alice', age: 30 };\n\n\u002F\u002F Optional properties\ninterface Config {\n  url: string;\n  timeout?: number; \u002F\u002F optional\n}\n\n\u002F\u002F Index signature (dynamic keys)\ninterface Dictionary {\n  [key: string]: string;\n}\nlet dict: Dictionary = { hello: 'world', foo: 'bar' };\n\n\u002F\u002F Readonly properties\ninterface Point {\n  readonly x: number;\n  readonly y: number;\n}\n\n\u002F\u002F Excess property check (error)\n\u002F\u002F let p: Person = { name: 'Bob', age: 25, email: 'bob@example.com' }; \u002F\u002F Error\n\n\u002F\u002F No error when assigning variable\nlet temp = { name: 'Bob', age: 25, email: 'bob@example.com' };\nlet person: Person = temp; \u002F\u002F OK, no excess check\n```\n\n**Practical Example:** An API response object with fixed fields and dynamic metadata: `interface Response { data: any; [key: string]: any; }`.\n\n**Common Mistakes:** Forgetting that index signatures require all properties to match the signature type. Using `object` type (non-primitive) vs `{}` vs `Record\u003Cstring, unknown>`.\n\n**Edge Cases:** `Object.create(null)` has no prototype; typed as `Record\u003Cstring, unknown>`. Empty type `{}` accepts any non-nullish value.\n\n**Interview Follow-ups:** \"What is the difference between `object`, `{}`, and `Object`?\" \"How do you type a dictionary with string keys and number values?\"\n\n**Best Practices:** Use interfaces for object shapes. Use `Record\u003CK, V>` for simple dictionaries. Use index signatures sparingly as they disable property checks.\n\n**Production Recommendations:** Prefer `Record\u003Cstring, unknown>` over `{[key: string]: any}` for safer dynamic objects.\n\n**Latest TypeScript Patterns:** `satisfies` operator helps avoid excess property checks while retaining inference.\n\n**Interview Tip:** Emphasize that excess property checks only apply to direct object literals; this is a common source of confusion.\n\n**Common Follow-up:** \"How do you make all properties optional?\" (Partial\u003CT>)\n\n**Real-world Example:** A configuration object that may have extra vendor-specific fields: `interface Config { timeout: number; [vendor: string]: unknown; }`.",[138,139,140,141],"objects","index-signature","excess-property","readonly",{"id":143,"category":144,"question":145,"answer":146,"level":10,"tags":147},17,"Generics","What are basic generics in TypeScript? How do you write a generic identity function?","**Concept Explanation:** Generics allow creating reusable components that work with multiple types while maintaining type safety. Instead of using `any`, generics capture the type parameter used when the function is called. This allows the function to preserve the input-output type relationship.\n\n**Internal Behavior:** When a generic function is called, TypeScript infers the type parameter from the arguments. You can also explicitly specify it. The compiler ensures that operations within the function are valid for any type that could be substituted.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Generic identity function\nfunction identity\u003CT>(value: T): T {\n  return value;\n}\n\n\u002F\u002F Usage with inference\nlet num = identity(5);      \u002F\u002F T inferred as number\nlet str = identity('hello'); \u002F\u002F T inferred as string\n\n\u002F\u002F Explicit type argument\nlet bool = identity\u003Cboolean>(true);\n\n\u002F\u002F Generic interface\ninterface Box\u003CT> {\n  value: T;\n}\n\nlet numberBox: Box\u003Cnumber> = { value: 42 };\nlet stringBox: Box\u003Cstring> = { value: 'hello' };\n\n\u002F\u002F Generic class\nclass Stack\u003CT> {\n  private items: T[] = [];\n  push(item: T) { this.items.push(item); }\n  pop(): T | undefined { return this.items.pop(); }\n}\n\nlet numberStack = new Stack\u003Cnumber>();\n```\n\n**Practical Example:** A `useState` hook implementation: `function useState\u003CT>(initial: T): [T, (value: T) => void]`.\n\n**Common Mistakes:** Using `any` instead of generics, losing type information. Forgetting that generic parameters are erased at runtime (can't do `value instanceof T`).\n\n**Edge Cases:** Generic constraints (`T extends SomeType`) restrict allowed types. Multiple type parameters are allowed. Default type parameters (`\u003CT = string>`) provide defaults.\n\n**Interview Follow-ups:** \"What is the difference between generic functions and overloads?\" \"Can you use generics with arrow functions?\"\n\n**Best Practices:** Use single uppercase letters (`T`, `U`, `V`) for simple generics. Use descriptive names (`TData`, `TError`) for complex cases. Add constraints to limit generic types.\n\n**Performance Considerations:** Generics are compile-time only; no runtime overhead.\n\n**Production Recommendations:** Always prefer generics over `any` for reusable functions. Use constraints to ensure necessary properties exist.\n\n**Latest TypeScript Patterns:** `const` type parameters (`\u003Cconst T>`) to infer literal types. Generic defaults with `=`.\n\n**Interview Tip:** The identity function is the classic example to explain generics. Emphasize that generics capture the type relationship, unlike `any` which discards it.\n\n**Common Follow-up:** \"How do you constrain a generic to only accept objects with a `length` property?\"\n\n**Real-world Example:** A utility function `getProperty\u003CT, K extends keyof T>(obj: T, key: K)` that safely returns `obj[key]` with proper return type.",[148,149,150,151],"generics","identity","type-parameters","reusability",{"id":153,"category":154,"question":155,"answer":156,"level":10,"tags":157},18,"Classes","How do you define classes with access modifiers in TypeScript?","**Concept Explanation:** TypeScript extends ES6 classes with access modifiers: `public` (default), `private`, `protected`. `private` members are only accessible within the class. `protected` members are accessible within the class and subclasses. TypeScript also supports `readonly` properties and parameter properties (shorthand constructor assignment).\n\n**Internal Behavior:** Access modifiers are compile-time only; at runtime, they become regular properties (no privacy). TypeScript's `private` uses hard private names, while ES2022 `#private` is runtime private.\n\n**Syntax & Code Example:**\n```ts\nclass Animal {\n  public name: string;\n  private age: number;\n  protected species: string;\n  readonly id: number;\n\n  \u002F\u002F Parameter property (shorthand)\n  constructor(name: string, age: number, public owner: string) {\n    this.name = name;\n    this.age = age;\n    this.id = Math.random();\n  }\n\n  public greet(): void {\n    console.log(`Hello, I'm ${this.name}`);\n  }\n\n  private getAge(): number {\n    return this.age;\n  }\n}\n\nclass Dog extends Animal {\n  constructor(name: string, age: number, owner: string) {\n    super(name, age, owner);\n    this.species = 'canine'; \u002F\u002F protected accessible\n    \u002F\u002F this.age is private, cannot access\n  }\n}\n```\n\n**Practical Example:** A bank account class: `private balance` prevents external modification, `protected accountNumber` allows subclasses to view but not expose publicly.\n\n**Common Mistakes:** Thinking `private` provides runtime encapsulation (it doesn't; use `#` for runtime private). Overusing `public` (it's default).\n\n**Edge Cases:** TypeScript's `private` allows assignment from the same class even if the instance is different. `protected` members are accessible in subclasses but not from unrelated classes.\n\n**Interview Follow-ups:** \"What is the difference between TypeScript's `private` and ES2022's `#`?\" \"Can you access a private member from a class instance outside the class?\"\n\n**Best Practices:** Use `private` for implementation details, `protected` for inheritance, `public` (default) for API. Use `readonly` for immutable fields. Use parameter properties for concise constructors.\n\n**Performance Considerations:** No runtime performance difference; modifiers are erased.\n\n**Production Recommendations:** Use ES2022 `#private` if you need runtime privacy. Otherwise, TypeScript `private` is sufficient for compile-time checks.\n\n**Latest TypeScript Patterns:** `abstract` classes and methods. `override` keyword (TS 4.3+) to indicate overriding methods.\n\n**Interview Tip:** Clarify that TypeScript's access modifiers are a compile-time construct – they do not prevent runtime access (e.g., via `Object.keys` or `instance['privateField']`).\n\n**Common Follow-up:** \"What is a parameter property?\"\n\n**Real-world Example:** A React component class with `private` methods for internal logic and `public` methods for ref APIs. TypeScript ensures external code doesn't call internal methods.",[158,159,160,161,162],"classes","access-modifiers","private","protected","public",{"id":164,"category":165,"question":166,"answer":167,"level":10,"tags":168},19,"Type Assertions","What are type assertions in TypeScript? Explain `as`, `as const`, and the `as unknown as` pattern.","**Concept Explanation:** Type assertions tell the TypeScript compiler to treat a value as a specific type, overriding its inferred type. Unlike type casts in other languages, assertions do not change runtime values – they only affect compile-time type checking.\n\n**Internal Behavior:** The compiler accepts assertions when it has reason to believe the assertion is valid (type assertion from a more specific to a more general type is always allowed; the reverse may require `as unknown as Target`). Assertions are erased during compilation.\n\n**Syntax & Code Example:**\n```ts\nlet someValue: unknown = 'hello';\n\n\u002F\u002F 'as' syntax\nlet strLength: number = (someValue as string).length;\n\n\u002F\u002F Angle-bracket syntax (not allowed in JSX)\nlet strLength2: number = (\u003Cstring>someValue).length;\n\n\u002F\u002F as const (literal inference)\nlet colors = ['red', 'green', 'blue'] as const;\n\u002F\u002F colors type: readonly ['red', 'green', 'blue']\n\n\u002F\u002F Double assertion (as unknown as Target)\nlet num = 123;\nlet str = num as unknown as string; \u002F\u002F Dangerous!\n```\n\n**Practical Example:** When using `document.getElementById('app')`, TypeScript returns `HTMLElement | null`. If you know the element exists and is a `HTMLDivElement`, use `const app = document.getElementById('app') as HTMLDivElement`.\n\n**Common Mistakes:** Asserting when you're not sure (causes runtime errors). Overusing assertions instead of proper type guards. Using `as any` to bypass type checking.\n\n**Edge Cases:** `as const` makes the entire structure readonly and infers literal types. Double assertions (`as unknown as T`) can bypass type safety completely – use only when absolutely necessary.\n\n**Interview Follow-ups:** \"What is the difference between type assertion and type casting?\" \"When should you use `as const`?\"\n\n**Best Practices:** Prefer type guards over assertions. Use `as const` for object literals that should have literal types. Use assertions sparingly, only when you have external knowledge the compiler doesn't.\n\n**Performance Considerations:** No runtime impact.\n\n**Production Recommendations:** Enable ESLint rule `@typescript-eslint\u002Fconsistent-type-assertions` to enforce style. Avoid double assertions when possible.\n\n**Latest TypeScript Patterns:** `satisfies` operator (TS 4.9) is often better than `as` for checking literal types without widening.\n\n**Interview Tip:** Emphasize that `as const` is a powerful tool for creating literal types from objects or arrays, often used with `satisfies`.\n\n**Common Follow-up:** \"What is the difference between `as const` and `readonly`?\"\n\n**Real-world Example:** A routing configuration: `const routes = [{ path: '\u002F', component: Home }, { path: '\u002Fabout', component: About }] as const;` ensures the array and objects are readonly and path values are literal strings, enabling stricter type checking in route matching.",[169,170,171,172],"assertions","as","as-const","double-assertion",{"id":174,"category":175,"question":176,"answer":177,"level":10,"tags":178},20,"Keyof & Typeof","What are the `keyof` and `typeof` operators in TypeScript?","**Concept Explanation:** `keyof` takes an object type and produces a union of its keys as string literals. `typeof` (type-level) takes a value and returns its type. Together they enable powerful patterns like creating type-safe property accessors or deriving types from runtime values.\n\n**Internal Behavior:** `keyof` operates on types only. `typeof` (when used in type position) extracts the type of a variable or constant. The two are often combined: `type Keys = keyof typeof obj`.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F keyof example\ninterface Person {\n  name: string;\n  age: number;\n  address: string;\n}\ntype PersonKeys = keyof Person; \u002F\u002F 'name' | 'age' | 'address'\n\n\u002F\u002F typeof (type-level) example\nconst colors = { red: '#ff0000', green: '#00ff00', blue: '#0000ff' };\ntype ColorKey = keyof typeof colors; \u002F\u002F 'red' | 'green' | 'blue'\n\n\u002F\u002F Practical: type-safe getProperty function\nfunction getProperty\u003CT, K extends keyof T>(obj: T, key: K): T[K] {\n  return obj[key];\n}\n\n\u002F\u002F Using with class\nclass User {\n  name = 'Alice';\n  age = 30;\n}\ntype UserKeys = keyof User; \u002F\u002F 'name' | 'age'\n```\n\n**Practical Example:** A form field validator that maps field names to validation functions: `type FieldName = keyof FormData;` ensures only valid field names can be used.\n\n**Common Mistakes:** Using `typeof` at runtime (it's a type operator, not a runtime function). Confusing `keyof any` (string | number | symbol) with `keyof object`.\n\n**Edge Cases:** `keyof` on an interface with index signature returns `string | number`. `typeof` on a variable with `const` assertion gives literal types.\n\n**Interview Follow-ups:** \"What does `keyof any` return?\" \"How do you get the type of a function's return value?\" (ReturnType\u003CT>)\n\n**Best Practices:** Use `keyof typeof obj` to derive types from runtime constants. Use `keyof T` with generic constraints for type-safe property access.\n\n**Performance Considerations:** No runtime impact.\n\n**Production Recommendations:** Use `keyof` in mapped types and conditional types for advanced transformations. Avoid using `keyof` on arrays (keys are array indexes).\n\n**Latest TypeScript Patterns:** `keyof` works with `satisfies`. `typeof` can be used with `import('file').type` syntax.\n\n**Interview Tip:** Emphasize that `keyof` combined with generics enables the most common advanced pattern: type-safe property access.\n\n**Common Follow-up:** \"What is the difference between `typeof` at the type level and the JavaScript `typeof` operator?\"\n\n**Real-world Example:** A React component that accepts a `value` and an `onChange` handler typed to the value's property: `interface Props\u003CT> { data: T; onChange: \u003CK extends keyof T>(field: K, value: T[K]) => void; }`.",[179,180,181,182],"keyof","typeof","type-operators","property-access",{"id":184,"category":185,"question":186,"answer":187,"level":10,"tags":188},21,"TsConfig","What are the essential tsconfig.json compiler options? Explain target, module, strict, and lib.","**Concept Explanation:** `tsconfig.json` is the configuration file for TypeScript projects. It controls compiler behavior, output format, and strictness. Key options include `target` (ECMAScript version for output), `module` (module system), `strict` (enables all strict type-checking flags), `lib` (included type definitions), and `outDir` (output directory).\n\n**Internal Behavior:** The TypeScript compiler reads `tsconfig.json` to determine which files to compile (`files`, `include`, `exclude`), how to transform code (`target`, `module`), and how strictly to check types (`strict`, `noImplicitAny`, etc.).\n\n**Syntax & Code Example (tsconfig.json):**\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"ES2020\",              \u002F\u002F JavaScript version output\n    \"module\": \"NodeNext\",            \u002F\u002F Module system (Node.js ESM)\n    \"lib\": [\"ES2020\", \"DOM\"],        \u002F\u002F Type definitions to include\n    \"strict\": true,                   \u002F\u002F Enable all strict checks\n    \"esModuleInterop\": true,          \u002F\u002F Better CommonJS\u002FESM interop\n    \"skipLibCheck\": true,             \u002F\u002F Skip type checking of declaration files\n    \"forceConsistentCasingInFileNames\": true,\n    \"outDir\": \".\u002Fdist\",               \u002F\u002F Output directory\n    \"rootDir\": \".\u002Fsrc\",               \u002F\u002F Source root\n    \"declaration\": true,              \u002F\u002F Generate .d.ts files\n    \"sourceMap\": true                 \u002F\u002F Generate source maps\n  },\n  \"include\": [\"src\u002F**\u002F*\"],\n  \"exclude\": [\"node_modules\", \"dist\"]\n}\n```\n\n**Practical Example:** For a Node.js library, use `target: ES2020`, `module: NodeNext`. For a browser app, use `target: ES2020`, `module: ES2020`, `lib: [\"ES2020\", \"DOM\"]`.\n\n**Common Mistakes:** Setting `target` too low (e.g., ES5) causes larger output. Not setting `moduleResolution` when using `module: NodeNext`. Forgetting `esModuleInterop` causing import issues.\n\n**Edge Cases:** `strict` enables `noImplicitAny`, `strictNullChecks`, `strictFunctionTypes`, `strictBindCallApply`, `strictPropertyInitialization`, etc. `skipLibCheck` speeds up builds but may miss type errors in dependencies.\n\n**Interview Follow-ups:** \"What is the difference between `module: CommonJS` and `module: ESNext`?\" \"What does `isolatedModules` do?\"\n\n**Best Practices:** Always enable `strict: true`. Use `target: ES2020` or higher for modern environments. Use `module: NodeNext` for Node.js projects, `ESNext` for bundlers.\n\n**Performance Considerations:** `skipLibCheck: true` significantly speeds up compilation. Use `incremental: true` for faster rebuilds.\n\n**Production Recommendations:** Use separate `tsconfig.json` for tests (extends base config). Use `tsc --noEmit` for type checking in CI.\n\n**Latest TypeScript Patterns:** `moduleResolution: bundler` (TS 5.0+) for bundler projects. `verbatimModuleSyntax` for clean imports.\n\n**Interview Tip:** Emphasize that `strict: true` is non-negotiable for new projects – it catches many bugs. Also mention `noImplicitReturns` and `noUnusedLocals` as additional helpful flags.\n\n**Common Follow-up:** \"What is the purpose of `types` in compilerOptions?\"\n\n**Real-world Example:** A monorepo with shared types uses `references` in tsconfig to enable project references, improving build performance and type safety across packages.",[189,190,191,192,193],"tsconfig","compiler-options","strict","target","module",{"id":195,"category":196,"question":197,"answer":198,"level":10,"tags":199},22,"Basic Generics","How do you add constraints to generic types using `extends`?","**Concept Explanation:** Generic constraints limit the types that can be used with a generic. Using `extends` keyword, you can require that a type parameter must be a subtype of a specific type (e.g., must have a `length` property). Constraints enable the generic function to safely access properties of the generic type.\n\n**Internal Behavior:** The compiler checks that any type argument satisfies the constraint. Inside the function, TypeScript treats the generic parameter as having the constraint's type, so you can call methods or access properties defined on the constraint.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Constraint: T must have a .length property\nfunction logLength\u003CT extends { length: number }>(item: T): T {\n  console.log(item.length); \u002F\u002F OK, length is known\n  return item;\n}\n\nlogLength('hello');      \u002F\u002F string has length\nlogLength([1, 2, 3]);    \u002F\u002F array has length\n\u002F\u002F logLength(123);       \u002F\u002F Error: number does not have length\n\n\u002F\u002F Constraint using interface\ninterface HasId {\n  id: number;\n}\nfunction getIds\u003CT extends HasId>(items: T[]): number[] {\n  return items.map(item => item.id);\n}\n\n\u002F\u002F Multiple constraints (using intersection)\ntype StringOrNumber = string | number;\nfunction process\u003CT extends StringOrNumber>(value: T): T {\n  return value;\n}\n```\n\n**Practical Example:** A function that merges two objects: `function merge\u003CT extends object, U extends object>(a: T, b: U): T & U` ensures only objects are merged.\n\n**Common Mistakes:** Forgetting that constraints are checked at call time, not inside the function body (you can still call methods only on the constraint). Using `extends` with primitive types incorrectly.\n\n**Edge Cases:** You can constrain to `unknown` (no effect). Constraint can be a type parameter itself (`\u003CT, U extends T>`).\n\n**Interview Follow-ups:** \"What is the difference between `T extends object` and `T extends {}`?\" \"Can you use multiple constraints?\"\n\n**Best Practices:** Add constraints when your generic code needs to rely on specific properties. Use the smallest constraint necessary. Prefer constraints over `any` or `unknown`.\n\n**Performance Considerations:** No runtime impact.\n\n**Production Recommendations:** Use constraints to create safer APIs. Combine with `keyof` for advanced property constraints.\n\n**Latest TypeScript Patterns:** `const` type parameters can be constrained. `satisfies` works with constraints.\n\n**Interview Tip:** Emphasize that constraints enable generic functions to do more than just pass through values – they can safely operate on the generic type.\n\n**Common Follow-up:** \"Can you have a generic constraint that depends on another generic parameter?\"\n\n**Real-world Example:** A function `pluck\u003CT, K extends keyof T>(items: T[], key: K): T[K][]` uses both `keyof` and a constraint to ensure the key exists on the object.",[148,200,201],"constraints","extends",{"id":203,"category":204,"question":205,"answer":206,"level":10,"tags":207},23,"Readonly & Optional","How do you use `readonly` and optional properties (`?`) in TypeScript interfaces?","**Concept Explanation:** `readonly` properties cannot be reassigned after initialization. Optional properties (marked with `?`) may be omitted from objects. Both are compile-time features that help create safer interfaces.\n\n**Internal Behavior:** The compiler checks that `readonly` properties are not modified after creation. Optional properties allow `undefined` implicitly; accessing them requires a check or optional chaining.\n\n**Syntax & Code Example:**\n```ts\ninterface User {\n  readonly id: number;    \u002F\u002F cannot change after creation\n  name: string;\n  email?: string;         \u002F\u002F optional property\n}\n\nconst user: User = { id: 1, name: 'Alice' };\nuser.id = 2;              \u002F\u002F Error: Cannot assign to 'id' because it is a read-only property\nuser.email = 'alice@example.com'; \u002F\u002F OK, optional can be added\n\n\u002F\u002F Readonly array\nconst numbers: readonly number[] = [1, 2, 3];\nnumbers.push(4);          \u002F\u002F Error: Property 'push' does not exist on type 'readonly number[]'\n\n\u002F\u002F Readonly with index signature\ninterface ReadonlyDict {\n  readonly [key: string]: number;\n}\n```\n\n**Practical Example:** A configuration object that should not be modified after load: `interface Config { readonly apiUrl: string; readonly timeout: number; }`.\n\n**Common Mistakes:** Confusing `readonly` with `const` (const is for variables, readonly for properties). Using `readonly` on properties of objects that themselves can be reassigned (the property is read-only, but the object reference can change).\n\n**Edge Cases:** `readonly` does not make deep immutability; nested objects are still mutable. Use `Readonly\u003CT>` or `DeepReadonly\u003CT>` for deep immutability.\n\n**Interview Follow-ups:** \"What is the difference between `readonly` and `Readonly\u003CT>`?\" \"How do you make all properties optional?\" (Partial\u003CT>)\n\n**Best Practices:** Use `readonly` for fields that should not change after initialization (like IDs). Use optional properties for fields that may be absent in some instances. Prefer `readonly` arrays over mutable ones for function parameters.\n\n**Performance Considerations:** No runtime impact.\n\n**Production Recommendations:** Use `ReadonlyArray\u003CT>` for function parameters that should not be mutated. Use `as const` for literal objects to infer `readonly`.\n\n**Latest TypeScript Patterns:** `ReadonlySet\u003CT>`, `ReadonlyMap\u003CK,V>`. `exactOptionalPropertyTypes` for stricter optional handling.\n\n**Interview Tip:** Emphasize that `readonly` is a compile-time guard, not a runtime one. It's especially useful in TypeScript to prevent accidental mutations in large codebases.\n\n**Common Follow-up:** \"How can you make an entire interface deeply readonly?\"\n\n**Real-world Example:** A Redux state interface with `readonly` properties ensures reducers do not mutate state directly, aligning with immutable update patterns.",[141,96,208,209],"interfaces","immutability",[211,218,230,239,248,256,263,271,279,287,296,304,312,320,329,339,347,356,364,370,378,384,389],{"id":6,"category":212,"question":213,"answer":214,"level":215,"tags":216},"Advanced Generics","What are advanced generic patterns like generic constraints with `keyof`, default type parameters, and generic parameter default values?","**Concept Explanation:** Advanced generics go beyond simple identity functions. They include: generic constraints using `keyof` to restrict types to keys of another type, default type parameters (e.g., `\u003CT = string>`) that provide fallback types, and generic parameter default values. These patterns enable highly reusable and type-safe utilities.\n\n**Internal Behavior:** The compiler evaluates constraints and defaults at the call site or usage. Defaults are used when the generic argument is omitted or cannot be inferred. Constraints ensure the provided type argument meets requirements; otherwise, a type error occurs.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Generic constraint with keyof\nfunction getProperty\u003CT, K extends keyof T>(obj: T, key: K): T[K] {\n  return obj[key];\n}\n\n\u002F\u002F Default type parameter\ninterface ApiResponse\u003CTData = unknown> {\n  data: TData;\n  status: number;\n}\nconst res: ApiResponse = { data: {}, status: 200 }; \u002F\u002F TData defaults to unknown\n\n\u002F\u002F Multiple generics with defaults\nfunction createPair\u003CT = string, U = number>(a: T, b: U): [T, U] {\n  return [a, b];\n}\ncreatePair('hello', 42);       \u002F\u002F [string, number]\ncreatePair(123, 'world');      \u002F\u002F [number, string] – inference overrides default\n\n\u002F\u002F Generic parameter with constraint and default\ntype EventMap\u003CT extends string = string> = Record\u003CT, (...args: any[]) => void>;\n```\n\n**Practical Example:** A `useLocalStorage` hook that defaults to `string` but can be generic: `function useLocalStorage\u003CT = string>(key: string): [T | null, (value: T) => void]`.\n\n**Common Mistakes:** Over-constraining generics, making APIs inflexible. Using default parameters incorrectly when inference would be better.\n\n**Edge Cases:** Defaults are not used when TypeScript can infer the type. Defaults can refer to earlier type parameters (`\u003CT, U = T>`).\n\n**Interview Follow-ups:** \"How do you create a generic type that picks a subset of keys with specific value types?\" \"What is the difference between generic defaults and overloads?\"\n\n**Best Practices:** Use constraints to document requirements. Use defaults for backward compatibility when adding generics to existing APIs. Use `keyof` constraints for type-safe property access.\n\n**Performance Considerations:** No runtime impact.\n\n**Production Recommendations:** In library code, prefer defaults to maintain backward compatibility. In application code, rely on inference and explicit constraints.\n\n**Latest TypeScript Patterns:** `const` generic parameters (TS 5.0+): `\u003Cconst T>` to infer literal types. `satisfies` with generics.\n\n**Interview Tip:** Emphasize that `keyof` constraints are the most common advanced generic pattern, used in many utility types.\n\n**Common Follow-up:** \"How do you create a generic that accepts only functions returning a promise?\"\n\n**Real-world Example:** An ORM query builder: `class QueryBuilder\u003CTEntity, TKey extends keyof TEntity = 'id'>` allows specifying primary key with default.","intermediate",[148,200,179,217],"default-parameters",{"id":16,"category":219,"question":220,"answer":221,"level":215,"tags":222},"Utility Types","Explain the built-in utility types: Partial, Required, Pick, Omit, Record, Exclude, Extract, ReturnType, and Parameters.","**Concept Explanation:** Utility types are predefined generic types provided by TypeScript for common type transformations. They operate on existing types to create new ones, reducing boilerplate and improving type safety.\n\n**Internal Behavior:** These utilities are implemented using mapped types, conditional types, and other TypeScript features. They are evaluated at compile time and have no runtime footprint.\n\n**Syntax & Code Example:**\n```ts\ninterface User {\n  id: number;\n  name: string;\n  email: string;\n  age: number;\n}\n\n\u002F\u002F Partial: all properties optional\ntype PartialUser = Partial\u003CUser>; \u002F\u002F { id?: number; name?: string; ... }\n\n\u002F\u002F Required: all properties required (removes optionality)\ninterface Config { url?: string; timeout?: number; }\ntype RequiredConfig = Required\u003CConfig>; \u002F\u002F { url: string; timeout: number }\n\n\u002F\u002F Pick: subset of properties\ntype NameAndEmail = Pick\u003CUser, 'name' | 'email'>; \u002F\u002F { name: string; email: string }\n\n\u002F\u002F Omit: exclude properties\ntype WithoutEmail = Omit\u003CUser, 'email'>; \u002F\u002F { id, name, age }\n\n\u002F\u002F Record: key-value map\ntype UserMap = Record\u003Cstring, User>; \u002F\u002F { [key: string]: User }\n\n\u002F\u002F Exclude: remove types from union\ntype T1 = Exclude\u003C'a' | 'b' | 'c', 'a' | 'b'>; \u002F\u002F 'c'\n\n\u002F\u002F Extract: keep types from union\ntype T2 = Extract\u003C'a' | 'b' | 'c', 'a' | 'd'>; \u002F\u002F 'a'\n\n\u002F\u002F ReturnType: function return type\nfunction fetchData(): Promise\u003CUser[]> { return fetch('\u002Fusers').then(r => r.json()); }\ntype Data = ReturnType\u003Ctypeof fetchData>; \u002F\u002F Promise\u003CUser[]>\n\n\u002F\u002F Parameters: tuple of parameter types\nfunction log(message: string, level: 'info' | 'error'): void {}\ntype LogParams = Parameters\u003Ctypeof log>; \u002F\u002F [string, 'info' | 'error']\n```\n\n**Practical Example:** In Redux, `type ActionCreators = Record\u003Cstring, (...args: any[]) => Action>`.\n\n**Common Mistakes:** Using `Pick\u003CT, K>` when K is a union of keys not present – TypeScript errors. Confusing `Exclude` (removes) with `Extract` (keeps).\n\n**Edge Cases:** `ReturnType` on overloaded functions uses the last overload. `Parameters` on generic functions returns types with generic parameters.\n\n**Interview Follow-ups:** \"How would you implement `Partial` yourself?\" \"What is the difference between `Pick` and `Omit`?\"\n\n**Best Practices:** Use utility types instead of manually writing transformed interfaces. Prefer `Omit` over `Pick` when excluding a few properties from a large interface.\n\n**Performance Considerations:** No runtime cost; they are compile-time only.\n\n**Production Recommendations:** Use `Record\u003Cstring, unknown>` for flexible dictionaries. Use `Pick` to limit API responses.\n\n**Latest TypeScript Patterns:** `Awaited\u003CT>` (TS 4.5+) for unwrapping promises. `NoInfer\u003CT>` (TS 5.4+) for type inference control.\n\n**Interview Tip:** Emphasize that mastering utility types is essential for writing advanced TypeScript code without boilerplate.\n\n**Common Follow-up:** \"What utility type would you use to make all properties nullable?\"\n\n**Real-world Example:** An API client: `type UpdatePayload\u003CT> = Partial\u003CPick\u003CT, 'id'>> & Omit\u003CPartial\u003CT>, 'id'>` allows partial updates but always includes id.",[223,224,225,226,227,228,229],"utility-types","partial","pick","omit","record","exclude","returntype",{"id":23,"category":231,"question":232,"answer":233,"level":215,"tags":234},"Mapped Types","What are mapped types in TypeScript and how do you create custom ones?","**Concept Explanation:** Mapped types allow creating new types based on existing ones by transforming each property. They use the syntax `{ [P in K]: T }` where K is a union of keys. You can add modifiers like `readonly` or `?` and also remove them using `-` prefixes.\n\n**Internal Behavior:** The compiler iterates over each key in the key union, applies the transformation, and constructs a new object type. Mapped types are evaluated during type checking and have no runtime representation.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Basic mapped type: make all properties optional\ntype Partial\u003CT> = {\n  [P in keyof T]?: T[P];\n};\n\n\u002F\u002F Custom mapped type: make all properties readonly\ntype Readonly\u003CT> = {\n  readonly [P in keyof T]: T[P];\n};\n\n\u002F\u002F Adding ? and readonly modifiers\ntype Nullable\u003CT> = {\n  [P in keyof T]: T[P] | null;\n};\n\n\u002F\u002F Removing modifiers (with -)\ntype Required\u003CT> = {\n  [P in keyof T]-?: T[P]; \u002F\u002F remove optional\n};\n\n\u002F\u002F Mapping over arbitrary union (not just keys of T)\ntype Getters\u003CT> = {\n  [K in keyof T as `get${Capitalize\u003Cstring & K>}`]: () => T[K];\n};\n\ninterface Person {\n  name: string;\n  age: number;\n}\ntype PersonGetters = Getters\u003CPerson>;\n\u002F\u002F { getName: () => string; getAge: () => number; }\n```\n\n**Practical Example:** A `DeepReadonly` mapped type that recursively makes all properties readonly.\n\n**Common Mistakes:** Forgetting to use `keyof` to iterate over keys. Not handling index signatures correctly. Using mapped types on non-object types.\n\n**Edge Cases:** Mapped types with `as` clause (key remapping) introduced in TS 4.1. Filtering keys using `as` with `never`.\n\n**Interview Follow-ups:** \"How do you create a mapped type that makes all properties functions?\" \"What is the difference between mapped types and index signatures?\"\n\n**Best Practices:** Use mapped types to implement custom utility types. Combine with `keyof` and `never` for filtering keys. Use `as` for key remapping.\n\n**Performance Considerations:** Complex mapped types can increase compile time; avoid deep recursion on large types.\n\n**Production Recommendations:** Use built-in utility types when possible. Write custom mapped types only when necessary for domain-specific transformations.\n\n**Latest TypeScript Patterns:** Key remapping with `as` (TS 4.1+). Filtering keys with `as never`. Template literal types in keys.\n\n**Interview Tip:** Emphasize that mapped types are the foundation of many utility types like `Partial`, `Readonly`, and `Pick`.\n\n**Common Follow-up:** \"How do you create a mapped type that only includes string properties?\"\n\n**Real-world Example:** A form library uses a mapped type to create validation schema from a data model: `type ValidationSchema\u003CT> = { [K in keyof T]: (value: T[K]) => string | undefined }`.",[235,236,237,238],"mapped-types","key-remapping","modifiers","custom-utilities",{"id":30,"category":240,"question":241,"answer":242,"level":215,"tags":243},"Conditional Types","How do conditional types work in TypeScript? Explain with examples and the `infer` keyword.","**Concept Explanation:** Conditional types have the form `T extends U ? X : Y`. They evaluate to `X` if type `T` is assignable to `U`, otherwise `Y`. The `infer` keyword allows capturing a type variable within a conditional type, enabling powerful type extraction and transformation.\n\n**Internal Behavior:** The compiler checks assignability, not equality. Distributive conditional types automatically distribute over union types. `infer` introduces a new type variable that is inferred from the matched part of the type.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Basic conditional type\ntype IsString\u003CT> = T extends string ? true : false;\ntype A = IsString\u003C'hello'>; \u002F\u002F true\ntype B = IsString\u003Cnumber>;  \u002F\u002F false\n\n\u002F\u002F Distributive conditional type (distributes over unions)\ntype ToArray\u003CT> = T extends any ? T[] : never;\ntype UnionToArray = ToArray\u003Cstring | number>; \u002F\u002F string[] | number[]\n\n\u002F\u002F Using infer to extract return type\ntype ReturnType\u003CT> = T extends (...args: any[]) => infer R ? R : never;\nfunction greet() { return 'hello'; }\ntype GreetReturn = ReturnType\u003Ctypeof greet>; \u002F\u002F string\n\n\u002F\u002F Infer array element type\ntype ElementType\u003CT> = T extends (infer U)[] ? U : never;\ntype E = ElementType\u003Cstring[]>; \u002F\u002F string\n\n\u002F\u002F Infer promise unwrapping\ntype Awaited\u003CT> = T extends Promise\u003Cinfer U> ? Awaited\u003CU> : T;\ntype Result = Awaited\u003CPromise\u003CPromise\u003Cnumber>>>; \u002F\u002F number\n```\n\n**Practical Example:** A type that checks if two types are equal: `type Equal\u003CX, Y> = (\u003CT>() => T extends X ? 1 : 2) extends (\u003CT>() => T extends Y ? 1 : 2) ? true : false;` (using a trick).\n\n**Common Mistakes:** Forgetting that conditional types distribute over unions, leading to unexpected results. Using `infer` in non-inferrable positions.\n\n**Edge Cases:** To stop distribution, wrap both sides in `[T] extends [U]`. `never` in conditional: `never extends T ? A : B` returns `never` (since never is empty union).\n\n**Interview Follow-ups:** \"What is distributive conditional typing?\" \"How do you prevent distribution?\"\n\n**Best Practices:** Use `infer` for extracting types from complex structures (promises, arrays, functions). Use conditional types for type-level logic.\n\n**Performance Considerations:** Recursive conditional types can cause deep recursion limits; use `@ts-ignore` or restructure.\n\n**Production Recommendations:** Prefer existing utility types (`ReturnType`, `Awaited`) over custom ones when possible.\n\n**Latest TypeScript Patterns:** Recursive conditional types (TS 4.1+). Template literal type inference with `infer`.\n\n**Interview Tip:** Emphasize that `infer` is the key to creating advanced type utilities like `ReturnType`, `Parameters`, `InstanceType`.\n\n**Common Follow-up:** \"How would you implement `Parameters\u003CT>` using conditional types and infer?\"\n\n**Real-world Example:** A type-safe event emitter: `type EventMap = { click: (event: MouseEvent) => void; keydown: (event: KeyboardEvent) => void; }; type EventHandler\u003CT extends keyof EventMap> = EventMap[T] extends (...args: infer P) => any ? P : never;` extracts parameter types.",[244,245,246,247],"conditional-types","infer","distribution","type-extraction",{"id":39,"category":249,"question":250,"answer":251,"level":215,"tags":252},"Type Guards & Narrowing","What are type guards and type narrowing techniques in TypeScript?","**Concept Explanation:** Type guards are expressions that perform runtime checks to assure the type of a variable in a certain scope. Type narrowing is the process by which TypeScript refines types based on guards, control flow, and other analysis.\n\n**Internal Behavior:** TypeScript uses control flow analysis to narrow unions based on checks like `typeof`, `instanceof`, `in`, equality checks, and user-defined type guard functions.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Built-in type guards: typeof, instanceof, in\nfunction process(value: string | number | Date) {\n  if (typeof value === 'string') {\n    value.toUpperCase(); \u002F\u002F string\n  } else if (typeof value === 'number') {\n    value.toFixed(2); \u002F\u002F number\n  } else {\n    value.getTime(); \u002F\u002F Date\n  }\n}\n\n\u002F\u002F User-defined type guard (returns value is Type)\ninterface Cat { meow(): void; }\ninterface Dog { bark(): void; }\nfunction isCat(animal: Cat | Dog): animal is Cat {\n  return (animal as Cat).meow !== undefined;\n}\n\nfunction handle(animal: Cat | Dog) {\n  if (isCat(animal)) {\n    animal.meow(); \u002F\u002F TypeScript knows it's Cat\n  } else {\n    animal.bark(); \u002F\u002F Dog\n  }\n}\n\n\u002F\u002F Using in operator\nif ('meow' in animal) { \u002F* Cat *\u002F }\n\n\u002F\u002F Assertion functions (asserts)\nfunction assertIsString(value: unknown): asserts value is string {\n  if (typeof value !== 'string') throw new Error('Not a string');\n}\n```\n\n**Practical Example:** A function that processes API responses that could be `User | ErrorResponse`. Use a type guard `isUser` to narrow.\n\n**Common Mistakes:** Forgetting that `typeof null` returns 'object'. Using `in` without narrowing correctly.\n\n**Edge Cases:** `instanceof` checks the prototype chain; works for classes but not interfaces. `in` works for checking property existence.\n\n**Interview Follow-ups:** \"What is the difference between `value is T` and `asserts value is T`?\" \"How does TypeScript narrow with discriminant properties?\"\n\n**Best Practices:** Prefer discriminated unions over custom type guards when possible. Use `is` for reusable type guards. Use `asserts` for validation functions.\n\n**Performance Considerations:** Type guards have runtime cost; keep them efficient.\n\n**Production Recommendations:** Use runtime validation libraries (Zod, io-ts) with type guards to ensure data from external sources.\n\n**Latest TypeScript Patterns:** `satisfies` operator works with narrowing. `using` declarations with type guards.\n\n**Interview Tip:** Emphasize that user-defined type guards are the bridge between runtime checks and compile-time types – a critical concept for handling uncertain data.\n\n**Common Follow-up:** \"How do you create a type guard for a discriminated union?\"\n\n**Real-world Example:** In a React app, fetching data: `if (isUser(data)) { setUser(data); } else { setError(data.message); }`.",[253,113,180,254,255],"type-guards","instanceof","in",{"id":50,"category":257,"question":258,"answer":259,"level":215,"tags":260},"Discriminated Unions","What are discriminated unions (tagged unions) and how do they enable exhaustive type checking?","**Concept Explanation:** A discriminated union is a union type with a common, literal-type property (the discriminant) that TypeScript can use to narrow the union. This pattern enables type-safe handling of different variants and exhaustive checking that all cases are covered.\n\n**Internal Behavior:** When you check the discriminant property (e.g., with `switch` or `if`), TypeScript narrows the union to the specific member. With exhaustiveness checking (using `never`), you can ensure all variants are handled.\n\n**Syntax & Code Example:**\n```ts\ntype Shape =\n  | { kind: 'circle'; radius: number }\n  | { kind: 'square'; side: number }\n  | { kind: 'triangle'; base: number; height: number };\n\nfunction area(shape: Shape): number {\n  switch (shape.kind) {\n    case 'circle':\n      return Math.PI * shape.radius ** 2;\n    case 'square':\n      return shape.side ** 2;\n    case 'triangle':\n      return (shape.base * shape.height) \u002F 2;\n    default:\n      \u002F\u002F Exhaustiveness check\n      const _exhaustive: never = shape;\n      return _exhaustive;\n  }\n}\n\n\u002F\u002F If you add a new variant, TypeScript errors here\n```\n\n**Practical Example:** Redux actions: `type Action = { type: 'ADD_TODO'; text: string } | { type: 'REMOVE_TODO'; id: number } | { type: 'TOGGLE_TODO'; id: number }`. The reducer switches on `action.type`.\n\n**Common Mistakes:** Forgetting the discriminant property on one of the union members. Using a discriminant that is not a literal type (e.g., `string` instead of `'type'`).\n\n**Edge Cases:** Discriminant can be a union of literals. You can have multiple discriminants using nested narrowing. `never` exhaustiveness check ensures future compatibility.\n\n**Interview Follow-ups:** \"How does exhaustiveness checking with `never` work?\" \"Can discriminated unions have more than one discriminant?\"\n\n**Best Practices:** Always include an exhaustiveness check in `default` or `else` to catch missing cases. Use `never` type for the checked value.\n\n**Performance Considerations:** No runtime cost beyond the discriminant check.\n\n**Production Recommendations:** Use discriminated unions for state machines, Redux reducers, API response handling, and any closed set of variants.\n\n**Latest TypeScript Patterns:** Exhaustive switch with `never` is standard. `satisfies` can enforce discriminant property.\n\n**Interview Tip:** Emphasize that discriminated unions + exhaustiveness checking is the TypeScript pattern for type-safe state machines, eliminating impossible states.\n\n**Common Follow-up:** \"How do you refactor a union into a discriminated union?\"\n\n**Real-world Example:** A game character state: `type CharacterState = { status: 'idle' } | { status: 'walking'; speed: number } | { status: 'attacking'; target: string }`. The game loop exhaustively handles each state, preventing bugs when adding new states.",[261,262,87,48],"discriminated-unions","tagged-unions",{"id":58,"category":264,"question":265,"answer":266,"level":215,"tags":267},"Intersection Types","What are intersection types and how do they differ from union types and interfaces?","**Concept Explanation:** Intersection types combine multiple types into one, containing all members of each constituent type. They are created with the `&` operator. Intersections are useful for merging objects, extending types, and creating ad-hoc combinations.\n\n**Internal Behavior:** The compiler checks that a value satisfies all constituent types. For object types, the resulting type has all properties. For function types, it represents overloaded functions. Intersections are commutative and associative.\n\n**Syntax & Code Example:**\n```ts\ninterface Person {\n  name: string;\n  age: number;\n}\n\ninterface Employee {\n  company: string;\n  salary: number;\n}\n\ntype PersonEmployee = Person & Employee;\n\u002F\u002F { name: string; age: number; company: string; salary: number }\n\n\u002F\u002F Intersection with primitive types (results in never)\ntype NeverType = string & number; \u002F\u002F never\n\n\u002F\u002F Intersection of functions (overload)\ntype Fn = ((x: string) => void) & ((x: number) => void);\n\u002F\u002F Equivalent to overloaded function\n\n\u002F\u002F Mixing with union\ntype Mixed = (string | number) & (string | boolean); \u002F\u002F string\n```\n\n**Practical Example:** A function that extends an object with additional properties: `function extend\u003CT, U>(obj: T, ext: U): T & U`.\n\n**Common Mistakes:** Confusing intersection with union (intersection = AND, union = OR). Assuming intersections are deep (they are shallow). Overusing intersections where interfaces with `extends` would be clearer.\n\n**Edge Cases:** Intersection of incompatible types yields `never`. Intersecting object types with contradictory property types also yields `never`. Intersection of call signatures creates overloads.\n\n**Interview Follow-ups:** \"What happens when you intersect two types with the same property name but different types?\" \"How does intersection work with generics?\"\n\n**Best Practices:** Use intersection for composing object types from existing ones. Prefer interfaces with `extends` for known hierarchies; use intersections for ad-hoc combination.\n\n**Performance Considerations:** No runtime impact.\n\n**Production Recommendations:** Use intersection to merge configuration objects or to add type information from multiple sources.\n\n**Latest TypeScript Patterns:** Intersections with template literal types. Intersection reduction in conditional types.\n\n**Interview Tip:** Emphasize the difference: `A & B` means the value must be both A and B (has all properties), while `A | B` means it can be either. This is a common confusion.\n\n**Common Follow-up:** \"How do you create a type that is a combination of two interfaces?\"\n\n**Real-world Example:** In a React component, `type Props = OwnProps & WithChildren & WithClassName` combines multiple concerns into one props type.",[268,269,270],"intersection","type-composition","combining-types",{"id":66,"category":272,"question":273,"answer":274,"level":215,"tags":275},"Declaration Merging","What is declaration merging in TypeScript and how can you use it to extend existing types?","**Concept Explanation:** Declaration merging is when TypeScript combines multiple declarations of the same name into a single definition. This works for interfaces (properties merged), namespaces (merged into a single namespace), and enums (merged with same name). Declaration merging allows extending existing types without modifying original definitions.\n\n**Internal Behavior:** The compiler collects all declarations of the same name and merges their members. For interfaces, properties are combined. For namespaces, exported members are merged. For enums, members are combined (values must be unique).\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Interface merging\ninterface User {\n  name: string;\n}\ninterface User {\n  age: number;\n}\n\u002F\u002F User now has both name and age\n\n\u002F\u002F Extending third-party types (e.g., Window interface)\ninterface Window {\n  myCustomAPI: {\n    doSomething(): void;\n  };\n}\n\u002F\u002F Now window.myCustomAPI is recognized\n\n\u002F\u002F Module augmentation (for module imports)\ndeclare module 'express' {\n  interface Request {\n    userId?: string;\n  }\n}\n\n\u002F\u002F Namespace merging\nnamespace Validation {\n  export interface StringValidator { isValid(s: string): boolean; }\n}\nnamespace Validation {\n  export const email: StringValidator = { isValid(s) { return s.includes('@'); } };\n}\n```\n\n**Practical Example:** In a Nuxt project, augmenting the Nuxt config type: `declare module '@nuxt\u002Fschema' { interface NuxtConfig { myCustomOption?: boolean; } }`.\n\n**Common Mistakes:** Trying to merge types (type aliases don't merge). Confusing merging with module augmentation syntax. Overusing global augmentation causing conflicts.\n\n**Edge Cases:** Interface merging can cause conflicts if properties have the same name but incompatible types (TypeScript errors). Namespace merging combines only exported members.\n\n**Interview Follow-ups:** \"What is module augmentation and when would you use it?\" \"How does declaration merging differ from extending a class?\"\n\n**Best Practices:** Use declaration merging sparingly for extending global types or third-party libraries. Prefer interfaces over types when you may need merging.\n\n**Performance Considerations:** No runtime impact.\n\n**Production Recommendations:** For global augmentations, put them in separate `.d.ts` files. Use `export {}` in modules to avoid unintentional global augmentation.\n\n**Latest TypeScript Patterns:** `declare global { ... }` for augmenting global scope within modules. Module augmentation in library `.d.ts` files.\n\n**Interview Tip:** Emphasize that declaration merging is unique to TypeScript and enables powerful extension patterns, especially for libraries and frameworks.\n\n**Common Follow-up:** \"How do you augment the Vue instance type?\"\n\n**Real-world Example:** In a Nuxt app, adding a custom `$api` property to the NuxtApp instance: `declare module '#app' { interface NuxtApp { $api: ApiClient; } }`.",[276,277,278],"declaration-merging","module-augmentation","global-augmentation",{"id":74,"category":280,"question":281,"answer":282,"level":215,"tags":283},"Function Overloading","How does function overloading work in TypeScript?","**Concept Explanation:** Function overloading in TypeScript allows defining multiple function signatures for the same function. The implementation signature is the only one that exists at runtime, but the overload signatures guide callers and type checking.\n\n**Internal Behavior:** The compiler matches the call against the overload list, picking the first applicable overload. The implementation must be compatible with all overload signatures. At runtime, there is no overloading; the function remains single.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Overload signatures\nfunction reverse(str: string): string;\nfunction reverse\u003CT>(arr: T[]): T[];\n\n\u002F\u002F Implementation signature\nfunction reverse(strOrArray: string | any[]): string | any[] {\n  if (typeof strOrArray === 'string') {\n    return strOrArray.split('').reverse().join('');\n  } else {\n    return [...strOrArray].reverse();\n  }\n}\n\nreverse('hello'); \u002F\u002F returns 'olleh'\nreverse([1, 2, 3]); \u002F\u002F returns [3, 2, 1]\n\n\u002F\u002F Overloading with different parameter counts\nfunction createDate(timestamp: number): Date;\nfunction createDate(year: number, month: number, day: number): Date;\nfunction createDate(a: number, b?: number, c?: number): Date {\n  if (b === undefined) return new Date(a);\n  return new Date(a, b, c || 1);\n}\n```\n\n**Practical Example:** A `document.createElement` style function: `createElement('div')` returns `HTMLDivElement`, `createElement('canvas')` returns `HTMLCanvasElement`.\n\n**Common Mistakes:** Implementation signature not being compatible with all overloads. Order of overloads matters (more specific to less specific). Overloading when a union type would suffice.\n\n**Edge Cases:** Using `never` for conditional overloads. Overloading with rest parameters. Overloading with generic constraints.\n\n**Interview Follow-ups:** \"What is the difference between overloads and union types?\" \"How many overloads can you have?\"\n\n**Best Practices:** Prefer union types for simple variations. Use overloads when the return type depends on the parameter type in complex ways that union types cannot express.\n\n**Performance Considerations:** No runtime impact; overloads are compile-time only.\n\n**Production Recommendations:** Use overloads for API functions that have different behavior based on parameter types (like `fetch` or `document.querySelector`).\n\n**Latest TypeScript Patterns:** Overloads with `const` generics. Overloads with conditional types in return.\n\n**Interview Tip:** Emphasize that overloads are primarily for better caller experience and documentation, not for multiple implementations.\n\n**Common Follow-up:** \"How do you type `addEventListener` overloads?\"\n\n**Real-world Example:** A DOM library: `function on\u003CT extends keyof HTMLElementEventMap>(el: HTMLElement, event: T, listener: (e: HTMLElementEventMap[T]) => void): void` uses overloads for different event types.",[284,285,286],"overloading","function-signatures","implementation",{"id":82,"category":288,"question":289,"answer":290,"level":215,"tags":291},"Modules","How do ES modules and namespace modules work in TypeScript?","**Concept Explanation:** TypeScript supports both ES modules (import\u002Fexport) and legacy namespaces. ES modules are the standard for modern TypeScript\u002FJavaScript, providing module isolation, tree-shaking, and better tooling. Namespaces (internal modules) are TypeScript-specific, designed for organizing code before ES modules existed.\n\n**Internal Behavior:** ES modules are processed according to the `module` compiler option (CommonJS, ES2020, NodeNext, etc.). Namespaces are compiled to immediately-invoked function expressions (IIFEs) that create nested objects. TypeScript's `moduleResolution` determines how module imports are resolved.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F ES Modules\n\u002F\u002F math.ts\nexport function add(a: number, b: number): number { return a + b; }\nexport const PI = 3.14;\nexport default class Calculator {}\n\n\u002F\u002F app.ts\nimport Calculator, { add, PI } from '.\u002Fmath.js';\n\n\u002F\u002F Namespaces (legacy, avoid)\nnamespace Validation {\n  export interface StringValidator { isValid(s: string): boolean; }\n  export class EmailValidator implements StringValidator {\n    isValid(s: string) { return s.includes('@'); }\n  }\n}\n\nconst validator = new Validation.EmailValidator();\n\n\u002F\u002F Using namespace merging (useful for types)\ntype Validator = Validation.StringValidator;\n```\n\n**Practical Example:** In a modern TypeScript project, use ES modules exclusively. Use `type` imports for type-only imports to improve performance.\n\n**Common Mistakes:** Mixing namespaces and ES modules (confusing). Using `export =` and `import = require()` for CommonJS interop. Not setting `module` and `moduleResolution` correctly.\n\n**Edge Cases:** `import type` vs `import` for types only. `export * as ns` syntax. Namespace merging with classes.\n\n**Interview Follow-ups:** \"What is the difference between `import type` and `import`?\" \"How do you configure TypeScript for Node.js ESM?\"\n\n**Best Practices:** Use ES modules for all new code. Avoid namespaces. Use `module: NodeNext` for Node.js projects.\n\n**Performance Considerations:** ES modules allow tree-shaking; namespaces do not. `import type` reduces runtime overhead.\n\n**Production Recommendations:** Use `isolatedModules: true` to ensure safe transpilation with bundlers. Use `verbatimModuleSyntax` (TS 5.0+) for clean imports.\n\n**Latest TypeScript Patterns:** `type` modifier in import. `moduleResolution: bundler` for modern bundlers.\n\n**Interview Tip:** Emphasize that namespaces are legacy and should not be used in new projects. ES modules are the standard.\n\n**Common Follow-up:** \"How do you organize types across multiple files?\" (Export\u002Fimport types)\n\n**Real-world Example:** In a large codebase, using `import type { User } from '.\u002Ftypes'` ensures the import is erased at runtime, improving build performance.",[292,293,294,295],"modules","es-modules","namespaces","import-export",{"id":89,"category":297,"question":298,"answer":299,"level":215,"tags":300},"Decorators","What are decorators in TypeScript and how are they used?","**Concept Explanation:** Decorators are special declarations that can be attached to classes, methods, properties, or parameters. They are a stage 2 ECMAScript proposal, and TypeScript implements an experimental version. Decorators allow metaprogramming: modifying behavior, adding metadata, or logging without changing the original code.\n\n**Internal Behavior:** When a decorator is applied, TypeScript calls the decorator function with specific arguments (target, name, descriptor, etc.) at runtime. The decorator can replace the original declaration or augment it.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Enable decorators in tsconfig.json: \"experimentalDecorators\": true\n\n\u002F\u002F Class decorator\nfunction logClass(constructor: Function) {\n  console.log(`Class created: ${constructor.name}`);\n}\n\n@logClass\nclass Person {}\n\n\u002F\u002F Method decorator\nfunction logMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) {\n  const original = descriptor.value;\n  descriptor.value = function(...args: any[]) {\n    console.log(`Calling ${propertyKey} with`, args);\n    return original.apply(this, args);\n  };\n}\n\nclass Calculator {\n  @logMethod\n  add(a: number, b: number) { return a + b; }\n}\n\n\u002F\u002F Property decorator\nfunction readonly(target: any, propertyKey: string) {\n  Object.defineProperty(target, propertyKey, { writable: false });\n}\n\nclass User {\n  @readonly\n  name: string = 'Alice';\n}\n\n\u002F\u002F Parameter decorator\nfunction logParam(target: any, methodName: string, paramIndex: number) {\n  console.log(`${methodName} param at index ${paramIndex} decorated`);\n}\n```\n\n**Practical Example:** In Angular, `@Component`, `@Injectable`, `@Input` are decorators. In NestJS, `@Controller`, `@Get`, `@Post` are decorators.\n\n**Common Mistakes:** Forgetting to enable `experimentalDecorators`. Assuming decorators work natively in JavaScript (they don't yet). Using decorators with `--strict` flag may have issues.\n\n**Edge Cases:** Decorators run at class definition time, not instance creation. Multiple decorators apply in reverse order (bottom to top).\n\n**Interview Follow-ups:** \"What is the difference between decorators and higher-order functions?\" \"What are the different types of decorators?\"\n\n**Best Practices:** Use decorators for cross-cutting concerns (logging, timing, authentication). Document decorator behavior clearly. Use reflect-metadata for more advanced decorator capabilities.\n\n**Performance Considerations:** Decorators have runtime cost; use sparingly in performance-critical code.\n\n**Production Recommendations:** For modern TypeScript, prefer alternatives (e.g., functions) unless using a framework that relies on decorators (Angular, NestJS).\n\n**Latest TypeScript Patterns:** Stage 3 decorators (TypeScript 5.0+) are different from experimental decorators. They use `$` prefix in metadata.\n\n**Interview Tip:** Emphasize that decorators are an experimental feature and their API may change. However, they are widely used in frameworks.\n\n**Common Follow-up:** \"How do you pass arguments to a decorator?\" (Use a decorator factory)\n\n**Real-world Example:** In a NestJS controller, `@Get('users')` decorator registers a route handler, and `@Req()` decorator injects the request object.",[301,302,303],"decorators","metaprogramming","experimental",{"id":98,"category":305,"question":306,"answer":307,"level":215,"tags":308},"Abstract Classes","What are abstract classes and methods in TypeScript?","**Concept Explanation:** Abstract classes are base classes that cannot be instantiated directly. They are designed to be extended by concrete subclasses. Abstract methods have no implementation in the abstract class and must be implemented by subclasses. Abstract classes provide a template for other classes.\n\n**Internal Behavior:** The compiler ensures that abstract classes are not instantiated and that all abstract methods are implemented in subclasses. Abstract classes can have concrete methods and properties. At runtime, abstract classes exist and can be instantiated only via subclasses.\n\n**Syntax & Code Example:**\n```ts\nabstract class Animal {\n  abstract makeSound(): void; \u002F\u002F abstract method\n  \n  move(): void { \u002F\u002F concrete method\n    console.log('Moving...');\n  }\n  \n  constructor(public name: string) {}\n}\n\nclass Dog extends Animal {\n  makeSound(): void { \u002F\u002F must implement\n    console.log('Woof!');\n  }\n}\n\n\u002F\u002F const animal = new Animal('Generic'); \u002F\u002F Error: Cannot create an instance of an abstract class\nconst dog = new Dog('Buddy');\ndog.makeSound(); \u002F\u002F Woof!\ndog.move(); \u002F\u002F Moving...\n```\n\n**Practical Example:** A UI framework: abstract `Widget` class with abstract `render` method, concrete `Button`, `Input` subclasses provide implementations.\n\n**Common Mistakes:** Trying to instantiate an abstract class. Forgetting to implement abstract methods in subclass.\n\n**Edge Cases:** Abstract classes can have constructors that are called when subclass is instantiated. Abstract methods can have optional parameters.\n\n**Interview Follow-ups:** \"What is the difference between an abstract class and an interface?\" \"Can an abstract class implement an interface?\"\n\n**Best Practices:** Use abstract classes when you need to share code among related classes and enforce method implementation. Use interfaces for pure contracts.\n\n**Performance Considerations:** No significant runtime impact.\n\n**Production Recommendations:** Prefer interfaces for defining contracts; use abstract classes when you need default implementations or state.\n\n**Latest TypeScript Patterns:** Abstract construct signatures. Abstract properties (TypeScript 4.0+).\n\n**Interview Tip:** Emphasize that abstract classes provide a balance between interface (pure contract) and concrete class (full implementation).\n\n**Common Follow-up:** \"Can you have abstract static methods?\"\n\n**Real-world Example:** A plugin system: abstract `Plugin` class with abstract `run()` method and concrete `initialize()` method that all plugins share.",[309,310,311],"abstract-class","inheritance","oop",{"id":106,"category":313,"question":314,"answer":315,"level":215,"tags":316},"Indexed Access Types","What are indexed access types and how do you use them to access nested property types?","**Concept Explanation:** Indexed access types (also called lookup types) allow accessing the type of a property using the syntax `Type[Key]`. They can be used to extract the type of nested properties, array elements, and more.\n\n**Internal Behavior:** The compiler looks up the property type in the given type. If the index is a union, the result is a union of the property types. This works similarly to how JavaScript accesses object properties but at the type level.\n\n**Syntax & Code Example:**\n```ts\ninterface Person {\n  name: string;\n  age: number;\n  address: {\n    street: string;\n    city: string;\n  };\n  tags: string[];\n}\n\ntype NameType = Person['name']; \u002F\u002F string\ntype AddressType = Person['address']; \u002F\u002F { street: string; city: string }\ntype StreetType = Person['address']['street']; \u002F\u002F string\ntype TagElementType = Person['tags'][number]; \u002F\u002F string (array element type)\n\n\u002F\u002F With union key\ntype NameOrAge = Person['name' | 'age']; \u002F\u002F string | number\n\n\u002F\u002F Getting all keys\ntype AllValues = Person[keyof Person]; \u002F\u002F string | number | { street: string; city: string } | string[]\n\n\u002F\u002F With generic\ntype GetProperty\u003CT, K extends keyof T> = T[K];\nlet x: GetProperty\u003CPerson, 'name'> = 'hello';\n```\n\n**Practical Example:** A function that returns the type of a specific property: `function getProperty\u003CT, K extends keyof T>(obj: T, key: K): T[K]`.\n\n**Common Mistakes:** Using `T['property']` when `property` is not a valid key. Using `T[number]` on non-array types.\n\n**Edge Cases:** Indexed access with `const` assertion: `const obj = { a: 1, b: 2 } as const; type A = typeof obj['a'];` yields literal `1`. Accessing `T[number]` on a tuple gives union of tuple element types.\n\n**Interview Follow-ups:** \"How do you get the type of an array's element?\" \"How do you access deeply nested property types?\"\n\n**Best Practices:** Use indexed access types instead of manual repetition. Combine with `keyof` for dynamic property access.\n\n**Performance Considerations:** No runtime impact.\n\n**Production Recommendations:** Use indexed access types in generic functions to preserve precise return types.\n\n**Latest TypeScript Patterns:** Pattern matching with `infer` and indexed types. `NoInfer\u003CT>` with indexed access.\n\n**Interview Tip:** Emphasize that indexed access types are essential for building type-safe utilities like `Pick`, `Omit`, and `Partial`.\n\n**Common Follow-up:** \"How do you get the type of a function's parameter from a type?\"\n\n**Real-world Example:** In Redux, `type ActionPayload\u003CT extends keyof ActionMap> = ActionMap[T]['payload']` extracts payload type from action map.",[317,318,319],"indexed-access","lookup-types","property-type",{"id":116,"category":321,"question":322,"answer":323,"level":215,"tags":324},"Async & Promise Typing","How do you type async functions and Promises in TypeScript?","**Concept Explanation:** Async functions in TypeScript implicitly return a `Promise`. You can specify the resolved type using `Promise\u003CT>` as the return type. The compiler ensures that the returned value matches the promise type.\n\n**Internal Behavior:** An async function always returns a promise. If you return a value, it's wrapped in `Promise.resolve`. If you throw, it becomes a rejected promise. TypeScript's type checking ensures that the resolved type matches the annotation.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Basic async typing\nasync function fetchUser(id: number): Promise\u003CUser> {\n  const response = await fetch(`\u002Fusers\u002F${id}`);\n  return response.json(); \u002F\u002F must be Promise\u003CUser>\n}\n\n\u002F\u002F Error handling with async\nasync function fetchMaybe(): Promise\u003Cstring> {\n  if (Math.random() > 0.5) {\n    return 'success';\n  } else {\n    throw new Error('fail'); \u002F\u002F promise rejects with Error\n  }\n}\n\n\u002F\u002F Promise constructor\ntype ResolvedType = Promise\u003Cstring> extends Promise\u003Cinfer T> ? T : never; \u002F\u002F string\n\n\u002F\u002F Using Awaited\u003CT> utility (TS 4.5+)\ntype Result = Awaited\u003CPromise\u003Cstring>>; \u002F\u002F string\n\n\u002F\u002F Wrapping with Promise\nfunction delay(ms: number): Promise\u003Cvoid> {\n  return new Promise(resolve => setTimeout(resolve, ms));\n}\n```\n\n**Practical Example:** An API client: `async function getData\u003CT>(url: string): Promise\u003CT>` generic function.\n\n**Common Mistakes:** Forgetting to annotate the return type, causing `Promise\u003CT>` but inferred as `Promise\u003Cany>`. Returning a non-promise value without `await` (still works but may cause unexpected execution order).\n\n**Edge Cases:** `Promise\u003Cvoid>` vs `Promise\u003Cundefined>`. Async functions that never resolve (infinite loops) – type is `Promise\u003Cnever>`.\n\n**Interview Follow-ups:** \"What is the difference between `Promise.resolve` and `async\u002Fawait`?\" \"How do you type a function that returns a promise of a union?\"\n\n**Best Practices:** Always annotate async function return types for clarity. Use `Awaited\u003CT>` to extract promise resolution type.\n\n**Performance Considerations:** No runtime type checking; promises are runtime constructs.\n\n**Production Recommendations:** Use `Awaited` to unwrap nested promises. Use `Promise.all` with proper typing: `Promise.all([fetch1, fetch2]) as Promise\u003C[Type1, Type2]>`.\n\n**Latest TypeScript Patterns:** `Awaited\u003CT>` recursive unwrap. `NoInfer\u003CT>` for promise chain inference.\n\n**Interview Tip:** Emphasize that `async\u002Fawait` is just syntactic sugar; understanding the underlying promise types is crucial.\n\n**Common Follow-up:** \"How do you type `Promise.allSettled`?\"\n\n**Real-world Example:** In a React component, `useEffect(() => { async function load() { const data = await api.get\u003CUser>('\u002Fme'); setUser(data); } load(); }, [])`.",[325,326,327,328],"async","promise","await","awaited",{"id":125,"category":330,"question":331,"answer":332,"level":215,"tags":333},"React with TypeScript","How do you type React components, props, and hooks (useState, useEffect, useRef) with TypeScript?","**Concept Explanation:** TypeScript enhances React development by typing component props, state, refs, and event handlers. This catches bugs early and improves autocompletion. Functional components use `React.FC` or explicit props typing. Hooks also accept type parameters for useState, useReducer, useRef, etc.\n\n**Internal Behavior:** TypeScript's JSX support maps HTML elements to intrinsic types. Generic hooks allow specifying state types. Event handlers use synthetic event types from `@types\u002Freact`.\n\n**Syntax & Code Example:**\n```tsx\nimport React, { useState, useEffect, useRef } from 'react';\n\n\u002F\u002F Props type\ninterface ButtonProps {\n  label: string;\n  onClick: () => void;\n  disabled?: boolean;\n}\n\n\u002F\u002F Component (React.FC or explicit)\nconst Button: React.FC\u003CButtonProps> = ({ label, onClick, disabled = false }) => {\n  return \u003Cbutton onClick={onClick} disabled={disabled}>{label}\u003C\u002Fbutton>;\n};\n\n\u002F\u002F useState with type\nconst [count, setCount] = useState\u003Cnumber>(0);\nconst [user, setUser] = useState\u003CUser | null>(null);\n\n\u002F\u002F useEffect (no special typing)\nuseEffect(() => {\n  document.title = `Count: ${count}`;\n}, [count]);\n\n\u002F\u002F useRef with HTML element\nconst inputRef = useRef\u003CHTMLInputElement>(null);\n\u003Cinput ref={inputRef} \u002F>;\n\n\u002F\u002F Event handler types\nconst handleChange = (e: React.ChangeEvent\u003CHTMLInputElement>) => {\n  console.log(e.target.value);\n};\n\nconst handleClick = (e: React.MouseEvent\u003CHTMLButtonElement>) => {\n  e.preventDefault();\n};\n\n\u002F\u002F Generic component\ninterface ListProps\u003CT> {\n  items: T[];\n  renderItem: (item: T) => React.ReactNode;\n}\nfunction List\u003CT>({ items, renderItem }: ListProps\u003CT>) {\n  return \u003Cul>{items.map(renderItem)}\u003C\u002Ful>;\n}\n```\n\n**Practical Example:** A form component with typed inputs and validation errors.\n\n**Common Mistakes:** Using `any` for event types. Forgetting to type `useRef` initial value as `null`. Using `React.FC` with children implicitly (React 18 removed).\n\n**Edge Cases:** `useRef` with mutable values (non-DOM) needs `MutableRefObject`. `useReducer` requires typing the state and actions.\n\n**Interview Follow-ups:** \"What is the difference between `React.FC` and typing props directly?\" \"How do you type `forwardRef`?\"\n\n**Best Practices:** Explicitly type props, not `React.FC`. Use `as const` for literal values. Use `typeof` for component props extraction.\n\n**Performance Considerations:** Types are erased at runtime; no performance impact.\n\n**Production Recommendations:** Use `@types\u002Freact` and `@types\u002Freact-dom`. Enable `strict` mode. Use `eslint-plugin-react` with TypeScript rules.\n\n**Latest TypeScript Patterns:** `satisfies` operator for props inference. `React.ComponentPropsWithoutRef\u003C'button'>` for extending native props.\n\n**Interview Tip:** Emphasize that typing React ensures component contracts are enforced, reducing runtime bugs.\n\n**Common Follow-up:** \"How do you type a custom hook?\"\n\n**Real-world Example:** A `useLocalStorage` hook: `function useLocalStorage\u003CT>(key: string, initialValue: T): [T, (value: T) => void]`.",[334,335,336,337,338],"react","props","hooks","events","refs",{"id":133,"category":340,"question":341,"answer":342,"level":215,"tags":343},"Vue with TypeScript","How do you type Vue components, props, emits, and refs with TypeScript?","**Concept Explanation:** Vue 3 has first-class TypeScript support. Composition API provides `defineProps`, `defineEmits`, `ref`, `computed`, and other functions that are generic for type safety. Options API also supports typing via `defineComponent`.\n\n**Internal Behavior:** Vue's type system uses declaration merging for component instances. `defineProps` and `defineEmits` are compile-time macros that provide full type inference. `ref` and `reactive` accept generics to enforce types.\n\n**Syntax & Code Example:**\n```vue\n\u003Cscript setup lang=\"ts\">\n\u002F\u002F Props with type\ninterface Props {\n  title: string;\n  count?: number;\n  user: { name: string; age: number };\n}\nconst props = defineProps\u003CProps>();\n\u002F\u002F With defaults\nconst props = withDefaults(defineProps\u003CProps>(), {\n  count: 0\n});\n\n\u002F\u002F Emits\ntype Emits = {\n  (e: 'update', value: number): void;\n  (e: 'close'): void;\n};\nconst emit = defineEmits\u003CEmits>();\n\u002F\u002F or simpler\nconst emit = defineEmits\u003C{ (e: 'update', value: number): void; (e: 'close'): void }>();\n\n\u002F\u002F Refs\nconst count = ref\u003Cnumber>(0);\nconst user = ref\u003CUser | null>(null);\nconst element = ref\u003CHTMLDivElement | null>(null);\n\n\u002F\u002F Computed\nconst doubled = computed\u003Cnumber>(() => count.value * 2);\n\n\u002F\u002F Reactive\ninterface State { name: string; age: number; }\nconst state = reactive\u003CState>({ name: '', age: 0 });\n\n\u002F\u002F Template ref with composable\nconst listRef = ref\u003CInstanceType\u003Ctypeof ListComponent> | null>(null);\n\n\u002F\u002F Options API with defineComponent\nexport default defineComponent({\n  props: {\n    title: { type: String, required: true },\n    count: { type: Number, default: 0 }\n  },\n  emits: ['update', 'close'],\n  setup(props) {\n    \u002F\u002F props.title is string\n  }\n});\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A todo item component with typed props (todo object) and emits (delete, update).\n\n**Common Mistakes:** Using `ref` without generic when initial value is `null` (infers `null` only). Forgetting to type `emit` payloads.\n\n**Edge Cases:** `reactive` cannot directly accept generic type from a function parameter. Use `as` or cast.\n\n**Interview Follow-ups:** \"How do you type a slot in Vue?\" \"What is the difference between `ref` and `shallowRef` typing?\"\n\n**Best Practices:** Use `defineProps\u003CProps>()` syntax. Always type emits. Use `InstanceType\u003Ctypeof Component>` for component refs.\n\n**Performance Considerations:** No runtime impact; types are stripped.\n\n**Production Recommendations:** Use `vue-tsc` for type checking. Enable `strict` mode in tsconfig.\n\n**Latest TypeScript Patterns:** `defineModel` (Vue 3.4+) for two-way bindings. Generic components with `\u003Cscript setup generic=\"T\">` (Vue 3.3+).\n\n**Interview Tip:** Emphasize that Vue's TypeScript support is excellent with Composition API; macros like `defineProps` are compile-time.\n\n**Common Follow-up:** \"How do you type a Vue composable?\"\n\n**Real-world Example:** A `useFetch` composable: `function useFetch\u003CT>(url: string): { data: Ref\u003CT | null>; error: Ref\u003CError | null>; loading: Ref\u003Cboolean> }`.",[344,335,345,338,346],"vue","emits","composables",{"id":143,"category":348,"question":349,"answer":350,"level":215,"tags":351},"TypeScript & Nuxt","How do you use TypeScript effectively in Nuxt 3? (auto-imports, pages, composables, runtimeConfig)","**Concept Explanation:** Nuxt 3 has built-in TypeScript support. It automatically generates types for auto-imported components, composables, and pages. The `nuxt.config.ts` is typed. Runtime config is typed via module augmentation. This provides full end-to-end type safety.\n\n**Internal Behavior:** Nuxt generates `.nuxt\u002Ftsconfig.json` and `.nuxt\u002Ftypes` with inferred types for pages, layouts, plugins, and auto-imports. The TypeScript compiler uses these to understand the Nuxt-specific features. Custom composables in `composables\u002F` are auto-imported with correct types.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F pages\u002Findex.vue – typed route params\n\u003Cscript setup lang=\"ts\">\n\u002F\u002F useRoute is typed from pages\u002F structure\nconst route = useRoute();\nconst { id } = route.params; \u002F\u002F string | string[]\n\n\u002F\u002F definePageMeta\n definePageMeta({\n  layout: 'default',\n  middleware: 'auth'\n});\n\n\u002F\u002F Typed runtimeConfig\nconst config = useRuntimeConfig();\nconsole.log(config.public.apiBase); \u002F\u002F typed\n\n\u002F\u002F Extend runtimeConfig types\n\u002F\u002F ~\u002Ftypes\u002Fnuxt.d.ts\ndeclare module 'nuxt\u002Fschema' {\n  interface RuntimeConfig {\n    public: {\n      apiBase: string;\n      siteUrl: string;\n    };\n    secretKey: string;\n  }\n}\n\n\u002F\u002F Typed composable auto-import\n\u002F\u002F composables\u002FuseUser.ts\nexport const useUser = () => {\n  const user = useState\u003CUser | null>('user', () => null);\n  return { user };\n};\n\n\u002F\u002F In component, useUser() is auto-imported and typed\n\n\u002F\u002F Typed server routes\n\u002F\u002F server\u002Fapi\u002Fusers\u002F[id].get.ts\nexport default defineEventHandler(async (event) => {\n  const id = getRouterParam(event, 'id'); \u002F\u002F string | undefined\n  const user = await getUser(id);\n  return user; \u002F\u002F automatically inferred\n});\n```\n\n**Practical Example:** A blog with dynamic pages: `pages\u002Fblog\u002F[slug].vue` – TypeScript infers `slug` from the route.\n\n**Common Mistakes:** Not generating types after adding pages or composables (Nuxt does this automatically). Overriding generated types incorrectly.\n\n**Edge Cases:** `useRoute().params` can be `string | string[]` for catch-all routes. Custom typing needed for complex params.\n\n**Interview Follow-ups:** \"How do you type custom middleware?\" \"How do you augment NuxtApp interface?\"\n\n**Best Practices:** Use `definePageMeta` with typed `validate` function. Extend `RuntimeConfig` in a `.d.ts` file. Use `import type` for types from Nuxt.\n\n**Performance Considerations:** Type generation happens at build time, no runtime overhead.\n\n**Production Recommendations:** Run `nuxi typecheck` to verify types. Enable `strict` in tsconfig.\n\n**Latest TypeScript Patterns:** `defineNuxtConfig` fully typed. `$fetch` typed with generics.\n\n**Interview Tip:** Emphasize that Nuxt 3's TypeScript support is opt-in but seamless; it's one of the framework's strengths.\n\n**Common Follow-up:** \"How do you type Nuxt plugins?\"\n\n**Real-world Example:** In a Nuxt app, define `useRequestHeaders` returns typed headers; `useCookie\u003CT>` is generic for cookie value types.",[352,353,354,355],"nuxt","auto-imports","runtimeConfig","pages",{"id":153,"category":357,"question":358,"answer":359,"level":215,"tags":360},"Error Handling","What are best practices for error handling and typing errors in TypeScript?","**Concept Explanation:** In TypeScript, error objects are typed as `unknown` because `catch` clause variables are `unknown` (or `any` with `useUnknownInCatchVariables: false`). You should narrow the error type using type guards before accessing properties like `message`. This prevents runtime crashes from malformed error objects.\n\n**Internal Behavior:** TypeScript's `useUnknownInCatchVariables` (enabled by default in `strict`) makes `catch(err)` have type `unknown`. You must validate the error shape (e.g., check if it has `message` and is an `Error` instance) before using it.\n\n**Syntax & Code Example:**\n```ts\ntry {\n  throw new Error('Something went wrong');\n} catch (err) {\n  \u002F\u002F err is unknown\n  if (err instanceof Error) {\n    console.log(err.message); \u002F\u002F safe\n  } else if (typeof err === 'string') {\n    console.log(err);\n  } else {\n    console.log('Unknown error', err);\n  }\n}\n\n\u002F\u002F Custom error type guard\nfunction isErrorWithMessage(error: unknown): error is { message: string } {\n  return typeof error === 'object' && error !== null && 'message' in error;\n}\n\ntry {\n  \u002F\u002F API call\n} catch (err) {\n  if (isErrorWithMessage(err)) {\n    console.log(err.message);\n  } else {\n    console.log('Unknown error');\n  }\n}\n\n\u002F\u002F Creating custom error classes\nclass ValidationError extends Error {\n  constructor(public field: string, message: string) {\n    super(message);\n    this.name = 'ValidationError';\n  }\n}\n\ntry {\n  throw new ValidationError('email', 'Invalid email');\n} catch (err) {\n  if (err instanceof ValidationError) {\n    console.log(`Field ${err.field}: ${err.message}`);\n  } else if (err instanceof Error) {\n    console.log(err.message);\n  }\n}\n```\n\n**Practical Example:** In an async function that fetches data, catch block should handle network errors, HTTP errors, and JSON parsing errors.\n\n**Common Mistakes:** Assuming `err` is always `Error`. Using `err.message` directly without type guard. Throwing non-Error objects (e.g., strings).\n\n**Edge Cases:** Third-party libraries may throw arbitrary values. `Promise` rejections can be any type.\n\n**Interview Follow-ups:** \"Why is `catch` error typed as `unknown`?\" \"How do you handle errors in async\u002Fawait?\"\n\n**Best Practices:** Always use `unknown` for catch variables. Use `instanceof Error` for built-in errors. Throw `Error` or custom Error subclasses, not strings.\n\n**Performance Considerations:** Type guards are runtime checks; minimal overhead.\n\n**Production Recommendations:** Use a centralized error handling utility that normalizes unknown errors. Use `assertIsError` function to validate.\n\n**Latest TypeScript Patterns:** `never` in exhaustive error handling. `cause` property in Error (ES2022) for error chaining.\n\n**Interview Tip:** Emphasize that TypeScript forces you to handle errors properly, reducing the chance of `Cannot read property 'message' of undefined` in production.\n\n**Common Follow-up:** \"How do you type a function that may throw?\"\n\n**Real-world Example:** In a Next.js API route, catch block checks if error is `ValidationError` to return 400, else 500.",[361,78,362,363],"error-handling","type-guard","custom-error",{"id":164,"category":365,"question":366,"answer":367,"level":215,"tags":368},"Strict Mode","What does `strict: true` enable in TypeScript and why is it recommended?","**Concept Explanation:** `strict: true` is a compiler option that enables a set of type-checking flags that catch common errors. It includes `noImplicitAny`, `strictNullChecks`, `strictFunctionTypes`, `strictBindCallApply`, `strictPropertyInitialization`, and `useUnknownInCatchVariables`. It's recommended for all new projects.\n\n**Internal Behavior:** These flags change how the compiler infers and checks types. For example, `strictNullChecks` makes `null` and `undefined` non-assignable to other types. `noImplicitAny` requires explicit types for parameters and variables when inference fails.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F With strict: true\nfunction add(a, b) { \u002F\u002F Error: Parameter 'a' implicitly has an 'any' type\n  return a + b;\n}\n\nlet name = null;\nname = 'Alice'; \u002F\u002F Error: Type 'string' is not assignable to type 'null'\n\nclass Person {\n  name: string; \u002F\u002F Error: Property 'name' has no initializer (strictPropertyInitialization)\n  constructor(name: string) {\n    this.name = name;\n  }\n}\n```\n\n**Practical Example:** Enabling `strict` catches potential null access, implicit any, and uninitialized class properties that would otherwise cause runtime errors.\n\n**Common Mistakes:** Disabling `strict` to quickly fix compiler errors. Not understanding each sub-flag's impact.\n\n**Edge Cases:** Migrating a large codebase to strict mode may require extensive changes. Use `strict: false` temporarily but plan to enable gradually.\n\n**Interview Follow-ups:** \"What does `strictPropertyInitialization` do?\" \"How do you gradually migrate to strict mode?\"\n\n**Best Practices:** Always enable `strict` for new projects. For existing projects, enable flags one by one starting with `noImplicitAny`.\n\n**Performance Considerations:** Strict mode may increase compile time slightly but improves type safety significantly.\n\n**Production Recommendations:** Use `strict: true` in production. For libraries, it's strongly recommended to ensure correct usage.\n\n**Latest TypeScript Patterns:** `strict` includes `useUnknownInCatchVariables` (TS 4.4+). `exactOptionalPropertyTypes` is separate.\n\n**Interview Tip:** Emphasize that `strict: true` is the baseline for modern TypeScript. Not using strict mode defeats the purpose of using TypeScript.\n\n**Common Follow-up:** \"What is the difference between `strict` and `noImplicitAny`?\"\n\n**Real-world Example:** After enabling `strictNullChecks`, a codebase revealed hundreds of potential null accesses that were previously ignored, preventing many `Cannot read property of null` errors in production.",[191,190,79,369],"noImplicitAny",{"id":174,"category":371,"question":372,"answer":373,"level":215,"tags":374},"Compiler Options","What are other important compiler options like `noUnusedLocals`, `noUnusedParameters`, `noImplicitReturns`, and `noFallthroughCasesInSwitch`?","**Concept Explanation:** These compiler options enforce code quality beyond strict type checking. They catch dead code, incomplete functions, and switch statement mistakes. They are not part of `strict` but are highly recommended.\n\n**Internal Behavior:** `noUnusedLocals` reports unused variables. `noUnusedParameters` reports unused function parameters. `noImplicitReturns` ensures all code paths in a function return a value. `noFallthroughCasesInSwitch` prevents accidental fallthrough.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F noUnusedLocals\nfunction process() {\n  const unused = 10; \u002F\u002F Error: 'unused' is declared but never used\n  const used = 20;\n  console.log(used);\n}\n\n\u002F\u002F noUnusedParameters\nfunction log(message: string, level?: string) {\n  \u002F\u002F level parameter not used -> error if noUnusedParameters\n  console.log(message);\n}\n\n\u002F\u002F noImplicitReturns\nfunction getValue(flag: boolean): number {\n  if (flag) {\n    return 42;\n  }\n  \u002F\u002F Missing return -> error\n}\n\n\u002F\u002F noFallthroughCasesInSwitch\nfunction handle(value: string) {\n  switch (value) {\n    case 'a':\n      console.log('a');\n    \u002F\u002F Fallthrough (no break) -> error if fallthrough cases\n    case 'b':\n      console.log('b');\n      break;\n  }\n}\n\n\u002F\u002F Suppressing with underscore\nfunction fetch(url: string, _options?: RequestInit) { \u002F\u002F _options not reported as unused\n  return fetch(url);\n}\n```\n\n**Practical Example:** In a large codebase, `noUnusedLocals` keeps code clean. `noImplicitReturns` ensures all branches return, preventing undefined runtime results.\n\n**Common Mistakes:** Disabling these because of linting errors – they indicate real issues. Using `_` prefix incorrectly (must be exactly `_` or start with `_`? It's convention, not enforced).\n\n**Edge Cases:** `noImplicitReturns` with void functions (no return needed) is fine. `noFallthroughCasesInSwitch` allows intentional fallthrough with `\u002F\u002F fallthrough` comment? Not by default; use `\u002F\u002F eslint-disable`.\n\n**Interview Follow-ups:** \"Why is `noImplicitReturns` important for functions returning promises?\" \"How do you ignore unused variable when destructuring?\"\n\n**Best Practices:** Enable all four in production projects. Use `_` prefix for intentionally unused parameters.\n\n**Performance Considerations:** No runtime impact; compile-time analysis only.\n\n**Production Recommendations:** Use `noUnusedLocals` and `noUnusedParameters` in CI to keep codebase clean. Use `noImplicitReturns` for all functions except those with `void`.\n\n**Latest TypeScript Patterns:** `noUnusedLocals` with `_` for unused destructuring: `const { _unused, used } = obj` still flags `_unused` unless you use `_` alone.\n\n**Interview Tip:** Emphasize that these options are low-hanging fruit for code quality. They catch bugs before runtime.\n\n**Common Follow-up:** \"What is the difference between `noUnusedLocals` and ESLint's `no-unused-vars`?\"\n\n**Real-world Example:** A team enabled `noImplicitReturns` and found a function that silently returned `undefined` in an edge case, causing a subtle bug in production. Fixing it prevented a customer-facing error.",[190,375,376,377],"no-unused-locals","no-implicit-returns","code-quality",{"id":184,"category":379,"question":380,"answer":381,"level":215,"tags":382},"Interface vs Type","What are the advanced differences between `interface` and `type` in TypeScript? Compare declaration merging, `extends`, `implements`, and performance.","**Concept Explanation:** Both `interface` and `type` can describe object shapes, but they have key differences: interfaces support declaration merging (multiple declarations with the same name combine); types do not. Interfaces can be extended with `extends` and implemented by classes; types use intersections (`&`). Types can represent unions, primitives, tuples, and advanced mapped\u002Fconditional types; interfaces cannot. Performance-wise, interfaces are cached and yield better error messages.\n\n**Internal Behavior:** The compiler merges multiple interface declarations into one, which is useful for augmenting existing types. For types, duplicate declarations cause errors. When checking object literals, interfaces are checked for excess properties; types behave similarly but with stricter merging rules.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Declaration merging (interface only)\ninterface User {\n  name: string;\n}\ninterface User {\n  age: number;\n}\n\u002F\u002F User now has name and age\n\n\u002F\u002F Type alias cannot merge\ntype UserType = { name: string };\n\u002F\u002F type UserType = { age: number }; \u002F\u002F Error: Duplicate identifier\n\n\u002F\u002F Extending vs intersecting\ninterface Animal { name: string; }\ninterface Dog extends Animal { bark(): void; }\n\ntype Cat = Animal & { meow(): void; };\n\n\u002F\u002F Implements (both work)\nclass Person implements User {\n  name = 'Alice';\n  age = 30;\n}\n\n\u002F\u002F Type alias for union (interface cannot)\ntype Status = 'active' | 'inactive';\n\n\u002F\u002F Type alias for tuple\ntype Point = [number, number];\n\n\u002F\u002F Mapped types (type only)\ntype Readonly\u003CT> = { readonly [P in keyof T]: T[P]; };\n\n\u002F\u002F Performance: interface caches better\n```\n\n**Practical Example:** In a library, use interface for public API to allow user augmentation. Use type for internal unions and complex transformations.\n\n**Common Mistakes:** Trying to merge types. Using `type` when you need declaration merging for global augmentations.\n\n**Edge Cases:** `type` can be recursive (`type Tree\u003CT> = { value: T; children: Tree\u003CT>[] };`). Interface can also be recursive but with a different syntax.\n\n**Interview Follow-ups:** \"Which one is faster for the compiler?\" \"Can you implement a type alias that is a union?\"\n\n**Best Practices:** Use `interface` for object shapes that may be extended or augmented. Use `type` for unions, tuples, primitives, and when you need mapped\u002Fconditional types.\n\n**Performance Considerations:** Interfaces are faster for type checking; types with complex unions\u002Fmapped types may be slower.\n\n**Production Recommendations:** For consistent API, prefer `interface` for exported object types. For internal utilities, `type` is fine.\n\n**Latest TypeScript Patterns:** `satisfies` works with both. `interface` can now extend from types that are object-like.\n\n**Interview Tip:** Emphasize that declaration merging is the killer feature of interfaces; types cannot do that.\n\n**Common Follow-up:** \"How do you augment an existing module's type definitions?\" (Use declaration merging with `interface`)\n\n**Real-world Example:** In a Node.js project, augmenting the global `ProcessEnv` interface: `declare namespace NodeJS { interface ProcessEnv { MY_CUSTOM_VAR: string; } }`.",[130,131,276,201,383],"implements",{"id":195,"category":385,"question":386,"answer":387,"level":215,"tags":388},"Extends vs Implements","What is the difference between `extends` and `implements` in TypeScript classes and interfaces?","**Concept Explanation:** `extends` is used for inheritance: a class or interface inherits members from a base class or interface, potentially overriding them. `implements` is used for contracts: a class declares that it conforms to an interface by providing implementations for all its members. A class can extend only one class but implement multiple interfaces.\n\n**Internal Behavior:** `extends` copies the implementation (methods, properties) from the base class. `implements` only checks that the class has the required shape; it does not provide any implementation or inheritance of behavior.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Base class\nclass Animal {\n  move() { console.log('Moving'); }\n}\n\n\u002F\u002F extends: inherits behavior\nclass Dog extends Animal {\n  bark() { console.log('Woof'); }\n}\nconst dog = new Dog();\ndog.move(); \u002F\u002F inherited\n\n\u002F\u002F Interface\ninterface Runnable {\n  run(): void;\n}\ninterface Swimmable {\n  swim(): void;\n}\n\n\u002F\u002F implements: provides implementation\nclass Athlete implements Runnable, Swimmable {\n  run() { console.log('Running'); }\n  swim() { console.log('Swimming'); }\n}\n\n\u002F\u002F Interface extending interface\ninterface Mammal extends Animal { \u002F\u002F Animal is a class, but TypeScript allows interface to extend class type\n  giveBirth(): void;\n}\n\n\u002F\u002F Class implementing interface with multiple inheritance (interface only)\nclass FlyingFish implements Runnable, Swimmable {\n  run() {}\n  swim() {}\n}\n```\n\n**Practical Example:** A UI component class `Button extends HTMLElement` (inheriting DOM methods) and `implements Clickable` (ensuring it has a `click()` method).\n\n**Common Mistakes:** Using `implements` when you need inheritance (no implementation is provided). Trying to `extend` multiple classes (use composition or interfaces).\n\n**Edge Cases:** A class can `extends` another class and also `implements` interfaces. An interface can `extends` a class (to capture its shape).\n\n**Interview Follow-ups:** \"Can a class implement multiple interfaces?\" \"Can an interface extend a class?\"\n\n**Best Practices:** Use `extends` for \"is-a\" relationships (inheritance). Use `implements` for \"can-do\" relationships (capabilities). Prefer composition over inheritance.\n\n**Performance Considerations:** No runtime difference; both are compile-time checks.\n\n**Production Recommendations:** Use `implements` to enforce contracts, `extends` sparingly to avoid deep inheritance hierarchies.\n\n**Latest TypeScript Patterns:** `implements` works with class expressions. `extends` now works with built-in constructors.\n\n**Interview Tip:** Emphasize that `implements` is a compile-time check only – it does not copy code. `extends` copies implementation.\n\n**Common Follow-up:** \"What is the difference between `extends` and `implements` for interfaces?\" (Both work, but `extends` merges interfaces; `implements` is for classes)\n\n**Real-world Example:** In a game, `class Player extends Character implements Drawable, Updateable`. `Character` provides health, movement implementation; `Drawable` and `Updateable` ensure the class has `draw()` and `update()` methods.",[201,383,310,208,158],{"id":203,"category":390,"question":391,"answer":392,"level":215,"tags":393},"API Response Typing","How do you type API responses in TypeScript with runtime validation (Zod, io-ts) and type predicates?","**Concept Explanation:** Static types only exist at compile time; API responses are dynamic at runtime. To ensure safety, you need runtime validation. Libraries like Zod and io-ts allow defining schemas that both validate data and infer TypeScript types. Type predicates (`is` guards) can be used to narrow unknown data to expected shapes.\n\n**Internal Behavior:** You define a schema (e.g., `z.object({...})`). At runtime, the schema validates the data and throws or returns a typed result. TypeScript infers the static type from the schema, ensuring consistency between compile-time and runtime.\n\n**Syntax & Code Example:**\n```ts\nimport { z } from 'zod';\n\n\u002F\u002F Define schema and infer type\nconst UserSchema = z.object({\n  id: z.number(),\n  name: z.string(),\n  email: z.string().email(),\n  age: z.number().optional(),\n});\ntype User = z.infer\u003Ctypeof UserSchema>;\n\nasync function fetchUser(id: number): Promise\u003CUser> {\n  const response = await fetch(`\u002Fapi\u002Fusers\u002F${id}`);\n  const data = await response.json();\n  \u002F\u002F Validate at runtime\n  return UserSchema.parse(data); \u002F\u002F throws if invalid\n}\n\n\u002F\u002F Safe parsing\nconst result = UserSchema.safeParse(data);\nif (result.success) {\n  console.log(result.data.name); \u002F\u002F typed as User\n} else {\n  console.error(result.error);\n}\n\n\u002F\u002F Custom type guard with validation\nfunction isUser(data: unknown): data is User {\n  return UserSchema.safeParse(data).success;\n}\n\n\u002F\u002F Using in code\nif (isUser(responseData)) {\n  \u002F\u002F responseData is User\n}\n```\n\n**Practical Example:** An API that returns `User | ErrorResponse`. Validate with discriminated union schema.\n\n**Common Mistakes:** Trusting static types alone (assuming API always returns correct shape). Not handling validation errors gracefully.\n\n**Edge Cases:** Partial responses, extra fields (Zod strips by default, can be configured). Date parsing: use `z.coerce.date()` or `z.string().datetime()`.\n\n**Interview Follow-ups:** \"What is the difference between `parse` and `safeParse`?\" \"How do you validate arrays?\"\n\n**Best Practices:** Always validate external data at runtime. Use Zod or similar for both validation and type inference. Use `safeParse` for recoverable errors.\n\n**Performance Considerations:** Validation adds runtime overhead; use only on boundaries (API responses, user input). For high-throughput, consider caching schemas.\n\n**Production Recommendations:** Use Zod for API client libraries. Define schemas in shared packages for frontend\u002Fbackend consistency.\n\n**Latest TypeScript Patterns:** Zod 4+ with `z.infer` and `z.output`. `zod-to-ts` for generating TypeScript from schemas.\n\n**Interview Tip:** Emphasize that TypeScript types alone are insufficient for external data; runtime validation is essential for reliability.\n\n**Common Follow-up:** \"How do you handle union responses (success\u002Ferror)?\"\n\n**Real-world Example:** A fetch wrapper: `async function fetchJSON\u003CT>(url: string, schema: z.ZodSchema\u003CT>): Promise\u003CT>` that validates every response, catching malformed data before it enters the application.",[394,395,396,397,398],"api","runtime-validation","zod","type-predicates","safeParse",[400,407,416,423,432,441,446,454,464,474,481,486,493,501,511,519,526,533,542,549,555,565,575,584,592],{"id":6,"category":401,"question":402,"answer":403,"level":404,"tags":405},"Advanced Infer","How does the `infer` keyword work in advanced conditional types? Can you give examples of extracting return types, promise unwrapping, and function parameters?","**Concept Explanation:** `infer` allows you to declare a type variable within a conditional type that is inferred from the matched type. It's used to extract and transform parts of complex types. The inferred variable can only be used in the true branch of the conditional type.\n\n**Internal Behavior:** When TypeScript evaluates `T extends infer U ? ... : ...`, it binds the actual type `T` to `U`. For `infer` in positions like array elements, promise resolution, or function returns, the compiler attempts to deduce the type from the structure.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Extract return type of a function\ntype ReturnType\u003CT> = T extends (...args: any[]) => infer R ? R : never;\nfunction greet() { return 'hello'; }\ntype R = ReturnType\u003Ctypeof greet>; \u002F\u002F string\n\n\u002F\u002F Extract parameter tuple\ntype Parameters\u003CT> = T extends (...args: infer P) => any ? P : never;\n\n\u002F\u002F Unwrap Promise recursively\ntype Awaited\u003CT> = T extends Promise\u003Cinfer U> ? Awaited\u003CU> : T;\ntype Result = Awaited\u003CPromise\u003CPromise\u003Cnumber>>>; \u002F\u002F number\n\n\u002F\u002F Extract array element type\ntype ElementType\u003CT> = T extends (infer U)[] ? U : T extends readonly (infer U)[] ? U : never;\n\n\u002F\u002F Extract first element of tuple\ntype First\u003CT extends any[]> = T extends [infer F, ...any[]] ? F : never;\ntype F = First\u003C[string, number, boolean]>; \u002F\u002F string\n\n\u002F\u002F More complex: extract from function with specific signature\ntype GetPromiseValue\u003CT> = T extends () => Promise\u003Cinfer U> ? U : never;\nasync function fetchData(): Promise\u003C{ id: number }> { return { id: 1 }; }\ntype Data = GetPromiseValue\u003Ctypeof fetchData>; \u002F\u002F { id: number }\n```\n\n**Practical Example:** A type that extracts the resolved value of a deeply nested promise or the response type of an async function.\n\n**Common Mistakes:** Using `infer` outside the `extends` clause. Trying to infer from a union in non-distributive way.\n\n**Edge Cases:** Multiple infer declarations in the same clause. Inferring from overloaded functions (uses last overload).\n\n**Interview Follow-ups:** \"How do you extract the last element of a tuple with `infer`?\" \"What happens if `infer` cannot match?\"\n\n**Best Practices:** Use `infer` for type extraction in utility types. Prefer built-in `ReturnType` and `Awaited` for common cases.\n\n**Performance Considerations:** Complex infer types can slow down compilation; use sparingly in large codebases.\n\n**Production Recommendations:** Use `infer` only when existing utility types are insufficient. Combine with constraints to limit recursion.\n\n**Latest TypeScript Patterns:** `infer ... extends` (TS 4.7+) allows adding constraints to inferred types: `infer U extends string`.\n\n**Interview Tip:** Emphasize that `infer` is the building block of advanced type manipulation. It's like pattern matching for types.\n\n**Common Follow-up:** \"How do you infer the type of a class method?\"\n\n**Real-world Example:** In a GraphQL client, infer the type of the data field from a query function: `type QueryResult\u003CT> = T extends () => Promise\u003C{ data: infer D }> ? D : never;`.","advanced",[245,244,247,406],"pattern-matching",{"id":16,"category":408,"question":409,"answer":410,"level":404,"tags":411},"Recursive Types","How do you define and use recursive types in TypeScript? Provide examples with JSON, tree structures, and deeply nested objects.","**Concept Explanation:** Recursive types are types that refer to themselves in their definition. They are essential for representing data structures like trees, linked lists, JSON objects, or file system hierarchies. TypeScript allows recursive type aliases and interfaces, but with constraints (must be indirect via object properties).\n\n**Internal Behavior:** The compiler checks recursion depth and may limit it (default ~50 levels). Recursive types are evaluated lazily; infinite recursion is prevented by heuristics. Type aliases must be used with object properties, not directly self-referential.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F JSON type (recursive)\ntype JSONValue = string | number | boolean | null | JSONObject | JSONArray;\ninterface JSONObject { [key: string]: JSONValue; }\ntype JSONArray = JSONValue[];\n\n\u002F\u002F Tree node\ninterface TreeNode\u003CT> {\n  value: T;\n  children: TreeNode\u003CT>[];\n}\n\n\u002F\u002F Linked list\ntype ListNode\u003CT> = { value: T; next: ListNode\u003CT> | null };\n\n\u002F\u002F Deep readonly (recursive mapped type)\ntype DeepReadonly\u003CT> = {\n  readonly [P in keyof T]: T[P] extends object ? DeepReadonly\u003CT[P]> : T[P];\n};\n\n\u002F\u002F File system\ninterface FileSystemNode {\n  name: string;\n  type: 'file' | 'directory';\n  content?: string;\n  children?: FileSystemNode[];\n}\n\n\u002F\u002F Flatten nested arrays recursively\ntype Flatten\u003CT> = T extends any[] ? (T[number] extends infer U ? (U extends any[] ? Flatten\u003CU> : U) : never) : T;\ntype Flat = Flatten\u003C[1, [2, [3, 4], 5], 6]>; \u002F\u002F 1 | 2 | 3 | 4 | 5 | 6\n```\n\n**Practical Example:** A function to deeply freeze an object: `function deepFreeze\u003CT>(obj: T): DeepReadonly\u003CT>`.\n\n**Common Mistakes:** Creating infinitely recursive type without a base case. Using recursive type alias directly (must be behind an object).\n\n**Edge Cases:** Recursive types with arrays need careful handling. Compiler may error on excessively deep recursion; restructure.\n\n**Interview Follow-ups:** \"How do you create a type for a nested path?\" \"What is the maximum recursion depth?\"\n\n**Best Practices:** Use interfaces for recursive structures (better performance). Provide an escape (e.g., `| null` or base case). Document recursion limit assumptions.\n\n**Performance Considerations:** Deep recursion can exponentially increase compile time; use tail recursion where possible.\n\n**Production Recommendations:** For very deep trees, consider runtime representations instead of compile-time types.\n\n**Latest TypeScript Patterns:** Tail recursion elimination for conditional types (TS 4.5+). Recursive template literal types.\n\n**Interview Tip:** Emphasize that recursive types are powerful for typing JSON, trees, and immutable transformations. They're a hallmark of advanced TypeScript.\n\n**Common Follow-up:** \"How would you type a path like `'user.address.city'` for dot notation?\" (Template literal and recursive types)\n\n**Real-world Example:** In a state management library, `DeepWritable\u003CDeepReadonly\u003CState>>` ensures immutability while allowing patches.",[412,413,414,415],"recursive-types","json","tree","deep-readonly",{"id":23,"category":417,"question":418,"answer":419,"level":404,"tags":420},"Template Literal Types","What are template literal types and how can they be used for string manipulation, type-safe string concatenation, and pattern matching?","**Concept Explanation:** Template literal types (TS 4.1+) allow creating types based on string literal patterns using the same syntax as JavaScript template literals. They enable powerful string manipulation at the type level, including concatenation, splitting, and pattern matching with `infer`.\n\n**Internal Behavior:** The compiler evaluates template literal types by substituting union types into placeholders, producing all possible combinations. When used with `infer` in conditional types, they can parse and extract parts of strings.\n\n**Syntax & Code Example:**\n```ts\ntype Greeting = `Hello, ${string}!`;\nlet g: Greeting = 'Hello, world!'; \u002F\u002F OK\ng = 'Hi'; \u002F\u002F Error\n\n\u002F\u002F Combining unions\ntype Direction = 'up' | 'down';\ntype Vertical = `${Direction}wards`; \u002F\u002F 'upwards' | 'downwards'\n\n\u002F\u002F Key renaming\ntype Getters\u003CT> = {\n  [K in keyof T as `get${Capitalize\u003Cstring & K>}`]: () => T[K];\n};\n\n\u002F\u002F Parse string with infer\ntype ExtractPath\u003CT extends string> = T extends `\u002Fapi\u002F${infer Path}\u002F${infer Id}`\n  ? { path: Path; id: Id }\n  : never;\ntype Params = ExtractPath\u003C'\u002Fapi\u002Fusers\u002F123'>; \u002F\u002F { path: 'users'; id: '123' }\n\n\u002F\u002F Build query string type\ntype QueryParams\u003CT extends Record\u003Cstring, string>> = {\n  [K in keyof T]: `${string & K}=${T[K]}`\n}[keyof T];\ntype Q = QueryParams\u003C{ sort: 'asc'; limit: '10' }>; \u002F\u002F 'sort=asc' | 'limit=10'\n\n\u002F\u002F Recursive template literal for dot notation paths\ntype Paths\u003CT> = T extends object ? {\n  [K in keyof T]: K extends string ? `${K}` | `${K}.${Paths\u003CT[K]>}` : never\n}[keyof T] : never;\n```\n\n**Practical Example:** A type-safe router: `type Route = `\u002Fusers\u002F${number}` | `\u002Fposts\u002F${string}``. The router can only accept valid patterns.\n\n**Common Mistakes:** Forgetting that template literal types only work with string literals, not `string` type (produces `string`). Using complex infer patterns that cause exponential blowup.\n\n**Edge Cases:** When a placeholder is a union, the result is a union of all combinations (Cartesian product). Can be huge.\n\n**Interview Follow-ups:** \"How do you split a string by a delimiter with template literals?\" \"What is the built-in `Uppercase\u003CT>` and how does it work?\"\n\n**Best Practices:** Use `Capitalize`, `Lowercase`, `Uppercase`, `Uncapitalize` utility types. Limit the size of unions to avoid compiler strain.\n\n**Performance Considerations:** Template literal types with many union combinations can cause slow type checking; use memoization or limit.\n\n**Production Recommendations:** Use for route parameters, CSS class builders, and type-safe event names.\n\n**Latest TypeScript Patterns:** Template literal types can be recursive (TS 4.7+). `satisfies` with template literals.\n\n**Interview Tip:** Emphasize that template literal types bring string parsing to the type level, enabling things like type-safe routing and ORM query builders.\n\n**Common Follow-up:** \"How would you validate an email format using template literal types?\"\n\n**Real-world Example:** In a GraphQL library, `type GraphQLQuery\u003CT extends string> = T` ensures that query strings start with `query` or `mutation` and have valid syntax.",[421,422,406,245],"template-literal","string-types",{"id":30,"category":424,"question":425,"answer":426,"level":404,"tags":427},"Variadic Tuples","What are variadic tuple types and how do they enable higher-order functions and type-safe function composition?","**Concept Explanation:** Variadic tuple types (TS 4.0+) allow working with tuples of unknown length using the spread operator (`...`). They enable functions to accept and return tuples that preserve element types and order, which is essential for higher-order functions like `compose`, `pipe`, and currying.\n\n**Internal Behavior:** The spread operator in type positions can capture a list of types. For example, `type Append\u003CT extends any[], U> = [...T, U]` adds an element to the end of a tuple. The compiler preserves the exact order and types of the spread elements.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Basic variadic tuple manipulation\ntype Prepend\u003CT extends any[], U> = [U, ...T];\ntype Append\u003CT extends any[], U> = [...T, U];\n\ntype Result = Append\u003C[string, number], boolean>; \u002F\u002F [string, number, boolean]\n\n\u002F\u002F Concatenate two tuples\ntype Concat\u003CT extends any[], U extends any[]> = [...T, ...U];\ntype ConcatResult = Concat\u003C[1, 2], [3, 4]>; \u002F\u002F [1, 2, 3, 4]\n\n\u002F\u002F Function to reverse tuple\ntype Reverse\u003CT extends any[]> = T extends [infer First, ...infer Rest] ? [...Reverse\u003CRest>, First] : [];\n\n\u002F\u002F Higher-order function: tuple of arguments preservation\nfunction tuple\u003CT extends any[]>(...args: T): T {\n  return args;\n}\n\n\u002F\u002F Variadic tuple inference in generics\nfunction zip\u003CT extends any[], U extends any[]>(\n  arr1: T,\n  arr2: U\n): [...T, ...U] {\n  return [...arr1, ...arr2];\n}\n\n\u002F\u002F Type-safe compose function\nfunction compose\u003CT extends any[], U, V>(\n  f: (arg: U) => V,\n  g: (...args: T) => U\n): (...args: T) => V {\n  return (...args) => f(g(...args));\n}\n```\n\n**Practical Example:** A function that prepends a logging function to a list of event handlers, preserving the handler signature.\n\n**Common Mistakes:** Not constraining the variadic type to `any[]`, causing inference failure. Using `...args` in type position without proper constraints.\n\n**Edge Cases:** Variadic tuples can be labeled. Empty tuple `[]` works correctly.\n\n**Interview Follow-ups:** \"How do you implement `pipe` with variadic tuples?\" \"What is the difference between `T[]` and `[...T]`?\"\n\n**Best Practices:** Use variadic tuples for higher-order functions to preserve argument types. Avoid deep recursion with large tuples.\n\n**Performance Considerations:** Compile time increases with tuple length; limit to reasonable sizes.\n\n**Production Recommendations:** Use built-in `Tuple` utility or custom types for libraries that need argument preservation.\n\n**Latest TypeScript Patterns:** Variadic tuples with labeled elements. Template literal types combined with variadic tuples.\n\n**Interview Tip:** Emphasize that variadic tuples are essential for writing strongly typed utilities that previously required overloads (e.g., `Promise.all`, `zip`, `compose`).\n\n**Common Follow-up:** \"How would you type a function that takes a list of callbacks and returns their combined return value?\"\n\n**Real-world Example:** In a Redux middleware, `applyMiddleware(...middlewares)` uses variadic tuples to preserve the signature of the final enhancer.",[428,429,430,431],"variadic-tuples","spread","compose","higher-order-functions",{"id":39,"category":433,"question":434,"answer":435,"level":404,"tags":436},"Branded Types","What are branded (nominal) types in TypeScript and how do they simulate nominal typing to avoid primitive obsession?","**Concept Explanation:** TypeScript uses structural typing, where types are compatible if their shapes match. Branded types (also called opaque types) add a unique marker to a type to create nominal-like behavior, preventing accidental assignment between compatible primitive types (e.g., `UserId` vs `ProductId` both are `string`).\n\n**Internal Behavior:** A branded type adds a unique property (e.g., `__brand`) that doesn't exist at runtime but makes the type incompatible with others. The compiler treats types with different brands as distinct, even if their underlying representations are identical.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Branded type pattern\ntype UserId = string & { readonly __brand: unique symbol };\ntype ProductId = string & { readonly __brand: unique symbol };\n\nfunction createUserId(id: string): UserId {\n  return id as UserId;\n}\nfunction createProductId(id: string): ProductId {\n  return id as ProductId;\n}\n\nfunction getUser(id: UserId) { \u002F* ... *\u002F }\n\nconst uid = createUserId('123');\nconst pid = createProductId('456');\ngetUser(uid); \u002F\u002F OK\ngetUser(pid); \u002F\u002F Error: Type 'ProductId' is not assignable to type 'UserId'\n\n\u002F\u002F Generic brand helper\ntype Brand\u003CT, B extends string> = T & { __brand: B };\ntype Email = Brand\u003Cstring, 'Email'>;\nfunction validateEmail(email: string): Email {\n  if (!email.includes('@')) throw new Error('Invalid email');\n  return email as Email;\n}\n\n\u002F\u002F Runtime erasure: brands don't exist\nconst email = validateEmail('test@example.com'); \u002F\u002F runtime type is string\n```\n\n**Practical Example:** In a payment system, `Dollars` and `Cents` are both numbers but should not be mixed. Branded types prevent passing cents where dollars are expected.\n\n**Common Mistakes:** Casting with `as` anywhere, breaking the brand. Not using a unique symbol, risking collision.\n\n**Edge Cases:** Brands are erased at runtime, so you cannot check them with `typeof`. Use runtime checks in creation functions.\n\n**Interview Follow-ups:** \"What is the difference between nominal and structural typing?\" \"How do you validate branded types at runtime?\"\n\n**Best Practices:** Use branded types for primitive domains (IDs, emails, currencies). Keep creation functions private to ensure brands are correctly applied.\n\n**Performance Considerations:** No runtime overhead; brands are erased.\n\n**Production Recommendations:** Use branded types for critical domains like monetary values, user IDs, and sanitized strings.\n\n**Latest TypeScript Patterns:** `unique symbol` for stronger nominal typing. `satisfies` with brands.\n\n**Interview Tip:** Emphasize that branded types solve the problem of primitive obsession in TypeScript, making APIs safer.\n\n**Common Follow-up:** \"How do you handle serialization of branded types?\"\n\n**Real-world Example:** In a banking app, `type AccountNumber = Brand\u003Cstring, 'AccountNumber'>` and `type RoutingNumber = Brand\u003Cstring, 'RoutingNumber'>`. A function `transfer(from: AccountNumber, to: AccountNumber)` cannot accidentally accept a routing number.",[437,438,439,440],"branded-types","nominal","primitive-obsession","opaque-types",{"id":50,"category":442,"question":443,"answer":444,"level":404,"tags":445},"Module Augmentation","How does module augmentation work? Explain with examples of extending third-party library types and global augmentations.","**Concept Explanation:** Module augmentation allows you to add new declarations to existing modules, interfaces, or namespaces without modifying the original source. This is useful for extending third-party libraries, adding custom properties to global objects, or merging types across files.\n\n**Internal Behavior:** TypeScript merges declarations that have the same name and scope. For modules, you use the `declare module 'module-name'` syntax inside a file that has no top-level import\u002Fexport (or with `export {}` to avoid global scope pollution).\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Augmenting the Express Request object\ndeclare module 'express' {\n  interface Request {\n    userId?: string;\n    context: { requestId: string };\n  }\n}\n\n\u002F\u002F After augmentation, req.userId is available\nimport { Request } from 'express';\nfunction handler(req: Request) {\n  console.log(req.userId); \u002F\u002F OK\n}\n\n\u002F\u002F Global augmentation (add to window)\ndeclare global {\n  interface Window {\n    __MY_APP_STATE__: any;\n  }\n}\nwindow.__MY_APP_STATE__ = { theme: 'dark' };\n\n\u002F\u002F Module augmentation for a specific file\n\u002F\u002F In a declaration file (e.g., types.d.ts)\ndeclare module '@nuxt\u002Fschema' {\n  interface NuxtConfig {\n    myCustomOption?: boolean;\n  }\n}\n\n\u002F\u002F Augmenting a class from a library\ndeclare module 'some-library' {\n  interface SomeClass {\n    newMethod(): void;\n  }\n}\n```\n\n**Practical Example:** In a Next.js app, augmenting the `NextPage` interface to add a custom `auth` property.\n\n**Common Mistakes:** Forgetting to use `export {}` in a module that has no imports (makes the file a script, polluting global). Over-augmenting without checking if the library already has the property.\n\n**Edge Cases:** Augmentation order matters; augmentations are global across the project. Cannot augment a module that is not loaded.\n\n**Interview Follow-ups:** \"What is the difference between module augmentation and declaration merging?\" \"How do you augment a module that has default export?\"\n\n**Best Practices:** Place augmentations in a `.d.ts` file or a dedicated `types\u002F` folder. Use `export {}` to ensure module scope. Avoid augmenting built-in types unless necessary.\n\n**Performance Considerations:** No runtime impact; compile-time only.\n\n**Production Recommendations:** For libraries, provide declaration merging interfaces to allow user augmentation. For apps, use module augmentation sparingly and document it.\n\n**Latest TypeScript Patterns:** Using `declare module '*!*'` for wildcard module augmentations (for bundler-specific imports).\n\n**Interview Tip:** Emphasize that module augmentation is a powerful escape hatch to extend types without forking dependencies, but it should be used with care.\n\n**Common Follow-up:** \"How do you augment the `ProcessEnv` interface in Node.js?\"\n\n**Real-world Example:** In a Nuxt project, augmenting `NuxtApp` to add a custom `$api` property: `declare module '#app' { interface NuxtApp { $api: ApiClient; } }`.",[277,276,278],{"id":58,"category":447,"question":448,"answer":449,"level":404,"tags":450},"Structural Typing","Explain structural vs nominal typing. How does TypeScript's structural typing affect type compatibility, and what are its limitations?","**Concept Explanation:** Structural typing means types are compatible if they have the same shape (property types), regardless of explicit declarations. Nominal typing requires explicit declaration of compatibility (e.g., class inheritance). TypeScript uses structural typing, which is flexible but can cause surprises when you expect nominal behavior.\n\n**Internal Behavior:** The compiler compares members of types recursively. Two interfaces with identical members are considered identical, even if they have different names. Excess properties are checked only on direct object literals.\n\n**Syntax & Code Example:**\n```ts\ninterface Person { name: string; }\ninterface Dog { name: string; }\n\nlet p: Person = { name: 'Alice' };\nlet d: Dog = { name: 'Buddy' };\np = d; \u002F\u002F OK, because shapes match\n\n\u002F\u002F This is often surprising\nclass User { name: string = ''; }\nclass Animal { name: string = ''; }\nlet u: User = new Animal(); \u002F\u002F OK\n\n\u002F\u002F To enforce nominal behavior, use branded types\ntype NamedUser = Person & { __brand: 'user' };\ntype NamedAnimal = Dog & { __brand: 'animal' };\n\n\u002F\u002F Structural typing limitation: excess property checks\ninterface Options { name: string; age?: number; }\nfunction setOpt(opt: Options) {}\nsetOpt({ name: 'John', email: 'john@x.com' }); \u002F\u002F Error: excess property 'email'\n\nconst extra = { name: 'John', email: 'john@x.com' };\nsetOpt(extra); \u002F\u002F OK, no excess property check\n```\n\n**Practical Example:** In a testing library, you can mock a service by providing an object with the same shape, no need to implement the full class.\n\n**Common Mistakes:** Assuming that different classes\u002Finterface names create distinct types. Over-relying on excess property checks for safety.\n\n**Edge Cases:** Functions are compared bivariantly for parameters (contravariant) and return types (covariant). Classes with private\u002Fprotected members become nominally typed.\n\n**Interview Follow-ups:** \"How does TypeScript compare function types?\" \"What is the difference between covariance and contravariance?\"\n\n**Best Practices:** Use branded types when you need nominal-like behavior. Accept structural typing for mocks and duck typing, but document expectations.\n\n**Performance Considerations:** Structural compatibility checking is O(members) but generally fast.\n\n**Production Recommendations:** For public APIs, use interfaces to describe shapes. For internal domain models, consider branded types to prevent accidental mixing.\n\n**Latest TypeScript Patterns:** `satisfies` operator preserves structural typing but adds constraints.\n\n**Interview Tip:** Emphasize that structural typing is what enables TypeScript's flexibility with JavaScript interoperability. It's a feature, not a bug.\n\n**Common Follow-up:** \"How do you make a class nominally typed?\" (Add a private member `private __nominal: void`)\n\n**Real-world Example:** A function `processPerson(data: Person)` can accept any object with a `name` property, even from different libraries. This is useful in integration code but can be dangerous for domain boundaries.",[451,438,452,453],"structural-typing","compatibility","duck-typing",{"id":66,"category":455,"question":456,"answer":457,"level":404,"tags":458},"Type Compatibility","Explain variance: covariance, contravariance, and bivariance in TypeScript function type compatibility.","**Concept Explanation:** Variance describes how subtyping between complex types relates to subtyping between their components. In TypeScript: return types are covariant (subtype of return is subtype of function), parameter types are contravariant (subtype of parameter makes function supertype), and under `strictFunctionTypes: false`, parameters are bivariant (both covariant and contravariant).\n\n**Internal Behavior:** With `strictFunctionTypes: true` (default in strict mode), function parameter types are checked contravariantly. This catches common errors like assigning `(animal: Animal) => void` to a variable expecting `(dog: Dog) => void` (which would be unsafe).\n\n**Syntax & Code Example:**\n```ts\nclass Animal { name = 'animal'; }\nclass Dog extends Animal { bark() {} }\n\n\u002F\u002F Covariant return type (OK)\ntype GetAnimal = () => Animal;\ntype GetDog = () => Dog;\nlet getAnimal: GetAnimal = () => new Animal();\nlet getDog: GetDog = () => new Dog();\ngetAnimal = getDog; \u002F\u002F OK: Dog is subtype of Animal\n\n\u002F\u002F Contravariant parameter type (with strictFunctionTypes)\ntype HandleAnimal = (a: Animal) => void;\ntype HandleDog = (d: Dog) => void;\nlet handleAnimal: HandleAnimal = (a) => {};\nlet handleDog: HandleDog = (d) => {};\nhandleDog = handleAnimal; \u002F\u002F OK: Animal handler can handle Dog\nhandleAnimal = handleDog; \u002F\u002F Error under strict: Dog handler cannot handle Animal\n\n\u002F\u002F Bivariant (when strictFunctionTypes false)\n\u002F\u002F Both assignments would be allowed\n\n\u002F\u002F Practical example: event listeners\ntype EventHandler\u003CT> = (event: T) => void;\nconst animalListener: EventHandler\u003CAnimal> = (a) => console.log(a.name);\nconst dogListener: EventHandler\u003CDog> = animalListener; \u002F\u002F OK contravariant\ndogListener(new Dog()); \u002F\u002F works\n```\n\n**Practical Example:** When using `Array.map`, the callback's return type covariance allows returning a subtype. Parameter contravariance is why you can pass `(event: MouseEvent) => void` to an `onClick` prop that expects `(event: React.MouseEvent) => void` if `MouseEvent` is a subtype.\n\n**Common Mistakes:** Not understanding variance leads to unsafe assignments or false positives. Turning off `strictFunctionTypes` for legacy code.\n\n**Edge Cases:** Method parameters are still bivariant even with `strictFunctionTypes` (by design for backward compatibility). Use arrow functions for stricter checking.\n\n**Interview Follow-ups:** \"Why are parameters contravariant?\" \"What is the safety rule?\"\n\n**Best Practices:** Keep `strictFunctionTypes: true`. Prefer arrow function types over method signatures for stricter variance.\n\n**Performance Considerations:** No runtime impact.\n\n**Production Recommendations:** Understand variance when designing callback-based APIs. Use `void` return type to allow callbacks returning any type.\n\n**Latest TypeScript Patterns:** `satisfies` with function types respects variance.\n\n**Interview Tip:** Emphasize that contravariance is often counterintuitive but essential for type safety. A function expecting `Dog` cannot handle `Animal` because it might call `bark()`.\n\n**Common Follow-up:** \"How does variance affect generic types?\"\n\n**Real-world Example:** React's `onChange` prop for inputs expects `(event: React.ChangeEvent\u003CHTMLInputElement>) => void`. You can pass a handler that expects `Event` (supertype) because of contravariance – the handler will work with the more specific event type.",[459,460,461,462,463],"variance","covariance","contravariance","bivariance","function-types",{"id":74,"category":465,"question":466,"answer":467,"level":404,"tags":468},"Performance Optimization","How do you optimize TypeScript compilation performance for large projects and monorepos?","**Concept Explanation:** TypeScript compilation can become slow in large codebases. Techniques include: using `project references` to split the build, `incremental` compilation, `skipLibCheck`, `isolatedModules` for faster transpilation with `ts-loader`, and using faster transpilers like `esbuild` or `swc` for type-checking separate from emitting.\n\n**Internal Behavior:** TypeScript's default checking involves parsing, binding, type checking, and emitting. Project references allow building dependencies first and reusing information. `incremental` saves information to `.tsbuildinfo` files. `skipLibCheck` avoids checking `node_modules` types.\n\n**Syntax & Code Example (tsconfig.json):**\n```json\n{\n  \"compilerOptions\": {\n    \"incremental\": true,\n    \"skipLibCheck\": true,\n    \"isolatedModules\": true,\n    \"declaration\": true,\n    \"declarationMap\": true,\n    \"sourceMap\": true\n  },\n  \"references\": [\n    { \"path\": \".\u002Fpackages\u002Fcore\" },\n    { \"path\": \".\u002Fpackages\u002Futils\" }\n  ]\n}\n```\n\n**Monorepo strategy:**\n```\npackages\u002F\n  core\u002F\n    tsconfig.json\n  utils\u002F\n    tsconfig.json\n  app\u002F\n    tsconfig.json (references core and utils)\n```\n\n**Using esbuild for transpilation (skip emit):**\n```bash\n# Type-check only\ntsc --noEmit\n# Transpile with esbuild\nnode esbuild.config.js\n```\n\n**Practical Example:** In a monorepo with 50 packages, `tsc --build` with project references builds only changed packages.\n\n**Common Mistakes:** Not using `incremental` in CI (but CI often has clean checkouts). Enabling `skipLibCheck` globally without caution. Using `ts-loader` in Webpack without `transpileOnly` and separate `fork-ts-checker`.\n\n**Edge Cases:** Project references require both `composite` and `declaration` flags. `isolatedModules` restricts some TypeScript features (e.g., const enums).\n\n**Interview Follow-ups:** \"What is the difference between `tsc --noEmit` and `tsc --build`?\" \"How do you speed up type checking in CI?\"\n\n**Best Practices:** Use `skipLibCheck` in development, but consider enabling in CI occasionally. Use `incremental` and store cache between CI runs. Use project references for logical separation.\n\n**Performance Considerations:** `isolatedModules` improves transpiler performance (esbuild). For large apps, separate type checking from transpilation.\n\n**Production Recommendations:** Use `tsc --noEmit` in CI for type safety, and `esbuild` or `swc` for fast builds. Use `turbo` or `nx` for monorepo orchestration.\n\n**Latest TypeScript Patterns:** `moduleResolution: bundler` (TS 5.0+) improves resolution speed. `verbatimModuleSyntax` simplifies imports.\n\n**Interview Tip:** Emphasize that the biggest gain often comes from separating type checking from emitting, especially in build pipelines.\n\n**Common Follow-up:** \"How do you configure TypeScript for Next.js?\"\n\n**Real-world Example:** A large e-commerce monorepo reduced build time from 8 minutes to 2 minutes by implementing project references, incremental builds, and using `esbuild` for transpilation while keeping `tsc --noEmit` for type checking in CI.",[469,470,471,472,473],"performance","monorepo","project-references","incremental","skipLibCheck",{"id":82,"category":475,"question":476,"answer":477,"level":404,"tags":478},"Zod Integration","How do you integrate Zod with TypeScript for runtime validation and type-safe API contracts?","**Concept Explanation:** Zod is a schema validation library that integrates seamlessly with TypeScript. You define a schema (e.g., `z.object(...)`), and Zod infers the static TypeScript type from it. This ensures that runtime validation matches compile-time types, eliminating discrepancies.\n\n**Internal Behavior:** Zod schemas are executable code that validate data at runtime. TypeScript's `z.infer\u003Ctypeof schema>` extracts the static type. The compiler ensures that the inferred type is consistent with the schema logic.\n\n**Syntax & Code Example:**\n```ts\nimport { z } from 'zod';\n\n\u002F\u002F Define schema and infer type\nconst UserSchema = z.object({\n  id: z.number(),\n  name: z.string().min(1),\n  email: z.string().email(),\n  age: z.number().int().positive().optional(),\n});\ntype User = z.infer\u003Ctypeof UserSchema>;\n\n\u002F\u002F Validate data\nconst rawData = { id: 1, name: 'Alice', email: 'alice@example.com' };\nconst user = UserSchema.parse(rawData); \u002F\u002F returns User (throws on failure)\n\n\u002F\u002F Safe parse\nconst result = UserSchema.safeParse(rawData);\nif (result.success) {\n  console.log(result.data.name); \u002F\u002F typed as User\n} else {\n  console.log(result.error);\n}\n\n\u002F\u002F API endpoint with validation\nexport default defineEventHandler(async (event) => {\n  const body = await readBody(event);\n  const validated = UserSchema.safeParse(body);\n  if (!validated.success) {\n    throw createError({ status: 400, message: validated.error.message });\n  }\n  \u002F\u002F validated.data is User\n});\n```\n\n**Practical Example:** A form validation utility that infers the form data type from a Zod schema, ensuring the form state and validation rules are consistent.\n\n**Common Mistakes:** Using `z.infer` but not actually validating at runtime. Defining schemas that are too permissive or too strict.\n\n**Edge Cases:** Zod can refine transformations: `z.string().refine(val => val.includes('@'), 'Must be email')`. Coercion: `z.coerce.number()`.\n\n**Interview Follow-ups:** \"How do you create a partial schema?\" \"What is the difference between `parse` and `safeParse`?\"\n\n**Best Practices:** Keep schemas in a shared location (e.g., `shared\u002Fschemas`) for frontend\u002Fbackend reuse. Use `.strict()` to forbid extra fields.\n\n**Performance Considerations:** Zod validation has overhead; for high-traffic APIs, consider caching compiled schemas or using `fastify` with built-in validation.\n\n**Production Recommendations:** Use Zod in both client and server to ensure data consistency. Use `z.infer` to derive types to avoid duplication.\n\n**Latest TypeScript Patterns:** Zod 4+ supports `z.instanceof`, `z.custom`, and better infer performance.\n\n**Interview Tip:** Emphasize that Zod solves the impedance mismatch between compile-time types and runtime data, which is a major pain point in TypeScript.\n\n**Common Follow-up:** \"How do you validate an API response with Zod?\"\n\n**Real-world Example:** In a TRPC API, the router uses Zod schemas for input validation. The client automatically gets the inferred types, and the server validates inputs, preventing malformed requests.",[396,395,479,480],"api-contracts","type-inference",{"id":89,"category":482,"question":483,"answer":484,"level":404,"tags":485},"Distributed Conditional Types","What are distributed conditional types? How do they work with unions and how can you prevent distribution?","**Concept Explanation:** A conditional type `T extends U ? X : Y` is distributive when `T` is a union type. The conditional type is applied to each member of the union, and the results are unioned together. This behavior is useful for mapping over unions (e.g., `Exclude\u003CT, U>` uses distribution). To prevent distribution, wrap `T` in a tuple `[T] extends [U] ? X : Y`.\n\n**Internal Behavior:** TypeScript automatically distributes conditionals over bare type parameters. For `type MyType\u003CT> = T extends string ? number : boolean`, if `T` is `string | number`, it becomes `(string extends string ? number : boolean) | (number extends string ? number : boolean)` = `number | boolean`.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Distributive conditional (default)\ntype ToArray\u003CT> = T extends any ? T[] : never;\ntype Result = ToArray\u003Cstring | number>; \u002F\u002F string[] | number[]\n\n\u002F\u002F Non-distributive (prevent distribution)\ntype ToArrayNonDist\u003CT> = [T] extends [any] ? T[] : never;\ntype Result2 = ToArrayNonDist\u003Cstring | number>; \u002F\u002F (string | number)[]\n\n\u002F\u002F Exclude implementation\ntype MyExclude\u003CT, U> = T extends U ? never : T;\ntype Filtered = MyExclude\u003C'a' | 'b' | 'c', 'a' | 'b'>; \u002F\u002F 'c'\n\n\u002F\u002F Use case: Filtering keys\ntype OnlyStringKeys\u003CT> = { [K in keyof T]: T[K] extends string ? K : never }[keyof T];\ntype Example = { a: string; b: number; c: string };\ntype Keys = OnlyStringKeys\u003CExample>; \u002F\u002F 'a' | 'c'\n```\n\n**Practical Example:** A generic `PickByType` utility that extracts keys where value matches a type.\n\n**Common Mistakes:** Assuming distribution always happens (only on bare type parameters). Forgetting distribution when writing custom utilities, leading to unexpected unions.\n\n**Edge Cases:** Distribution with `never` produces `never`. `any` and `unknown` also distribute but differently.\n\n**Interview Follow-ups:** \"How does `Exclude\u003CT, U>` work internally?\" \"How would you prevent distribution?\"\n\n**Best Practices:** Use distribution to map over unions. Wrap in `[]` when you need the union as a whole. Document distribution behavior.\n\n**Performance Considerations:** Distributing over large unions can blow up compile time.\n\n**Production Recommendations:** Use built-in `Exclude`, `Extract`, `NonNullable` which leverage distribution.\n\n**Latest TypeScript Patterns:** Distribution with `infer` and template literal types.\n\n**Interview Tip:** Emphasize that understanding distribution is key to writing advanced utility types like `Omit` and `Pick` workalikes.\n\n**Common Follow-up:** \"Is `T extends U ? X : Y` always distributive?\"\n\n**Real-world Example:** A type `DeepReadonly\u003CT>` uses distribution to apply recursively to each union member.",[244,246,111,228],{"id":98,"category":487,"question":488,"answer":489,"level":404,"tags":490},"Advanced Mapped Types","How do you create advanced mapped types like DeepReadonly, DeepPartial, and PathValue?","**Concept Explanation:** Advanced mapped types recursively transform object types. `DeepReadonly` makes all properties readonly at any depth. `DeepPartial` makes all properties optional. `PathValue` extracts the type of a nested property given a dot-notation path string. These require recursive type aliases and conditional types.\n\n**Internal Behavior:** The types use recursion: if a property is an object, apply the transformation recursively; otherwise, transform the primitive. For `PathValue`, a template literal conditional parses the path and walks the object type.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F DeepReadonly\ntype DeepReadonly\u003CT> = {\n  readonly [P in keyof T]: T[P] extends object ? DeepReadonly\u003CT[P]> : T[P];\n};\n\n\u002F\u002F DeepPartial\ntype DeepPartial\u003CT> = {\n  [P in keyof T]?: T[P] extends object ? DeepPartial\u003CT[P]> : T[P];\n};\n\n\u002F\u002F DeepRequired (all optional become required recursively)\ntype DeepRequired\u003CT> = {\n  [P in keyof T]-?: T[P] extends object ? DeepRequired\u003CT[P]> : T[P];\n};\n\n\u002F\u002F PathValue: get nested property type by dot path\ntype PathValue\u003CT, P extends string> = \n  T extends object\n    ? P extends `${infer K}.${infer Rest}`\n      ? K extends keyof T\n        ? PathValue\u003CT[K], Rest>\n        : never\n      : P extends keyof T\n        ? T[P]\n        : never\n    : never;\n\ntype Nested = { user: { profile: { age: number } } };\ntype Age = PathValue\u003CNested, 'user.profile.age'>; \u002F\u002F number\n\n\u002F\u002F PickByType\n type PickByType\u003CT, ValueType> = {\n  [P in keyof T as T[P] extends ValueType ? P : never]: T[P];\n};\n```\n\n**Practical Example:** In Redux, `DeepReadonly\u003CState>` ensures reducers don't mutate state.\n\n**Common Mistakes:** Infinite recursion on circular references (use `& object` or depth limit). Not handling arrays (treat as objects, but may want to preserve array methods).\n\n**Edge Cases:** For functions, you likely don't want to recurse into them; check for `Function`.\n\n**Interview Follow-ups:** \"How would you create `DeepWritable\u003CT>`?\" \"What about arrays?\"\n\n**Best Practices:** Add base case for arrays and functions. Use `T extends any[] ? T : ...` to preserve array identity.\n\n**Performance Considerations:** Deep recursion can be slow; limit depth or use Tail recursion.\n\n**Production Recommendations:** Use such types for configuration objects and state, but avoid on large data structures.\n\n**Latest TypeScript Patterns:** `Recursive` type aliases now easier. `satisfies` with deep types.\n\n**Interview Tip:** Emphasize that deep mapped types are the pinnacle of TypeScript type-level programming, showing mastery of recursion, conditional types, and key remapping.\n\n**Common Follow-up:** \"How do you make `DeepReadonly` skip certain properties?\"\n\n**Real-world Example:** An ORM's query builder uses `PathValue` to infer the return type from a dot-path selection string, enabling type-safe partial selects.",[235,415,491,492],"deep-partial","path-value",{"id":106,"category":494,"question":495,"answer":496,"level":404,"tags":497},"Declaration Files","How do you write and maintain declaration files (.d.ts) for JavaScript libraries? Explain ambient declarations, export patterns, and triple-slash directives.","**Concept Explanation:** Declaration files (`.d.ts`) provide TypeScript type information for plain JavaScript libraries. They describe module shapes, global variables, and functions. Ambient declarations (using `declare`) define types without runtime code. Triple-slash references (`\u002F\u002F\u002F \u003Creference \u002F>`) are legacy; prefer `import` or `export` in modern TS.\n\n**Internal Behavior:** The compiler reads `.d.ts` files during type checking. They are not emitted to JavaScript. TypeScript automatically includes `.d.ts` from `node_modules\u002F@types`. For your own JS, you can write custom declarations.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F globals.d.ts – declare global variables\ndeclare const MY_API_KEY: string;\ndeclare function log(message: string): void;\n\n\u002F\u002F module declaration for a legacy JS module\n\u002F\u002F my-library.d.ts\ndeclare module 'my-legacy-lib' {\n  export function initialize(config: { debug: boolean }): void;\n  export class Calculator {\n    add(a: number, b: number): number;\n  }\n  export const version: string;\n}\n\n\u002F\u002F Wildcard module (for file imports)\ndeclare module '*.svg' {\n  const content: string;\n  export default content;\n}\ndeclare module '*.css';\n\n\u002F\u002F CommonJS interop\ndeclare module 'old-lib' {\n  = require('old-lib');\n  export function doThing(): void;\n}\n\n\u002F\u002F Namespace (legacy pattern)\ndeclare namespace MyLib {\n  function doWork(): void;\n  let status: string;\n}\n```\n\n**Practical Example:** Writing a declaration for a vanilla JS library `date-utils` that exports a function `formatDate(date, format)`.\n\n**Common Mistakes:** Forgetting to mark module declarations as ambient (using `declare module`). Mixing module augmentations with regular exports.\n\n**Edge Cases:** Using `export =` for CommonJS modules. Triple-slash directives still used for `\u002F\u002F\u002F \u003Creference types=\"node\" \u002F>`.\n\n**Interview Follow-ups:** \"What is the difference between `declare module` and `declare namespace`?\" \"How do you publish a library with its own types?\"\n\n**Best Practices:** Prefer `export` over `declare global` when possible. Place custom declarations in a `types\u002F` folder. Use `@types` for third-party libraries.\n\n**Performance Considerations:** No runtime impact.\n\n**Production Recommendations:** For your own JS libraries, write `.d.ts` alongside source. Use `types` field in `package.json`.\n\n**Latest TypeScript Patterns:** `export type * from '...'` for re-exporting types. `module: nodenext` with `.d.ts` resolution.\n\n**Interview Tip:** Emphasize that declaration files are essential for consuming JS libraries in TypeScript. Knowing how to write them is a valuable skill.\n\n**Common Follow-up:** \"How do you generate `.d.ts` from TypeScript source?\" (tsc --declaration)\n\n**Real-world Example:** A Vue 2 library without types adds `types\u002F` folder with `declare module 'vue\u002Ftypes\u002Fvue' { interface Vue { $myPlugin: MyPluginType; } }` to augment Vue instance.",[498,499,500,277],"declaration-files","d.ts","ambient",{"id":116,"category":502,"question":503,"answer":504,"level":404,"tags":505},"Compiler Internals","Explain the TypeScript compilation flow: parsing, binding, type checking, and emitting. What are the key data structures like Symbol, Type, and Node?","**Concept Explanation:** TypeScript compilation pipeline: 1) **Parsing**: source code → AST (Node). 2) **Binding**: AST nodes → Symbols (identifier references). 3) **Type Checking**: Symbols and types are resolved, constraints checked. 4) **Emitting**: TypeScript AST → JavaScript output. Key data structures: `Node` (AST node), `Symbol` (named declaration), `Type` (type representation).\n\n**Internal Behavior:** The parser produces a `SourceFile` (root Node). The binder creates a `Symbol` for each declaration and links references to symbols. The type checker creates `Type` objects (interfaces, unions, intersections) and checks assignability. The emitter uses the `Transformation` pipeline to produce output.\n\n**Syntax & Code Example (conceptual):**\n```ts\n\u002F\u002F Source code\nlet x: number = 5;\n\n\u002F\u002F AST (simplified)\n{\n  kind: SyntaxKind.VariableStatement,\n  declarationList: {\n    kind: SyntaxKind.VariableDeclarationList,\n    declarations: [{\n      kind: SyntaxKind.VariableDeclaration,\n      name: { kind: SyntaxKind.Identifier, text: 'x' },\n      type: { kind: SyntaxKind.NumberKeyword },\n      initializer: { kind: SyntaxKind.NumericLiteral, text: '5' }\n    }]\n  }\n}\n\n\u002F\u002F Symbol for x: { name: 'x', flags: Variable, valueDeclaration: Node, type: NumberType }\n```\n\n**Practical Example:** Writing a custom TypeScript transformer to log all function calls. You traverse the AST and add console.log statements.\n\n**Common Mistakes:** Thinking type checking happens during emission (it's separate). Modifying the AST incorrectly in transformers.\n\n**Edge Cases:** The binder handles scope (functions, blocks, modules). The type checker can cause recursive type expansion.\n\n**Interview Follow-ups:** \"What is a Symbol vs a Type?\" \"How does the type checker handle circular references?\"\n\n**Best Practices:** Use the TypeScript Compiler API for custom transformations. Understand the pipeline for optimizing build tools.\n\n**Performance Considerations:** Binding and type checking are the most expensive phases. `skipLibCheck` skips type checking of library files.\n\n**Production Recommendations:** Use `tsc --traceResolution` for debugging module resolution. Use `tsc --generateTrace` to analyze performance.\n\n**Latest TypeScript Patterns:** The compiler now uses incremental building and semantic diagnostics caching.\n\n**Interview Tip:** Emphasize that understanding the compilation flow is essential for writing custom tools (linters, transformers) and optimizing build times.\n\n**Common Follow-up:** \"How would you write a plugin to remove debugger statements?\"\n\n**Real-world Example:** Angular's template compiler uses TypeScript's AST API to transform component templates into JavaScript code.",[506,507,508,509,510],"compiler","ast","binding","type-checking","emit",{"id":125,"category":512,"question":513,"answer":514,"level":404,"tags":515},"Custom Utility Types","How do you build custom utility types like `PickByValueType`, `OmitByType`, `Merge`, `PartialByKeys`, and `RequiredByKeys`?","**Concept Explanation:** Custom utility types extend TypeScript's built-in capabilities. They use mapped types, conditional types, key remapping, and `never` filtering. These utilities solve domain-specific problems like selecting properties by value type, merging two objects, or making specific keys partial.\n\n**Internal Behavior:** These types leverage key remapping (`as`) to filter keys. Conditional types test property types. Intersections combine object types. Built-in utilities (`Pick`, `Omit`) are building blocks.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F PickByType: choose keys where value matches a type\ntype PickByType\u003CT, V> = {\n  [P in keyof T as T[P] extends V ? P : never]: T[P];\n};\n\n\u002F\u002F OmitByType: opposite\ntype OmitByType\u003CT, V> = {\n  [P in keyof T as T[P] extends V ? never : P]: T[P];\n};\n\n\u002F\u002F Merge two types (shallow)\ntype Merge\u003CT, U> = Omit\u003CT, keyof U> & U;\n\n\u002F\u002F DeepMerge (simplified)\ntype DeepMerge\u003CT, U> = {\n  [K in keyof T | keyof U]: K extends keyof U\n    ? K extends keyof T\n      ? T[K] extends object && U[K] extends object\n        ? DeepMerge\u003CT[K], U[K]>\n        : U[K]\n      : U[K]\n    : K extends keyof T\n      ? T[K]\n      : never;\n};\n\n\u002F\u002F PartialByKeys: make specific keys optional\ntype PartialByKeys\u003CT, K extends keyof T> = Omit\u003CT, K> & Partial\u003CPick\u003CT, K>>;\n\n\u002F\u002F RequiredByKeys: make specific keys required\ntype RequiredByKeys\u003CT, K extends keyof T> = Omit\u003CT, K> & Required\u003CPick\u003CT, K>>;\n\n\u002F\u002F Example usage\ninterface User { id: number; name: string; age: number; email: string; }\ntype StringProps = PickByType\u003CUser, string>; \u002F\u002F { name: string; email: string; }\n```\n\n**Practical Example:** In a form library, `PartialByKeys\u003CFormData, 'optionalField'>` marks only specific fields as optional.\n\n**Common Mistakes:** Not handling union types correctly. Forgetting that `&` merges but doesn't resolve conflicts (use `Omit` first).\n\n**Edge Cases:** `never` keys are filtered out. Mapped types over `keyof T` with `as` remapping.\n\n**Interview Follow-ups:** \"How would you create a `DeepPick\u003CT, Path>` utility?\" \"What is the difference between `Merge` and `&`?\"\n\n**Best Practices:** Reuse built-in utilities. Test your utility types with example inputs. Document the behavior clearly.\n\n**Performance Considerations:** Complex custom utilities can increase compile time; use them sparingly.\n\n**Production Recommendations:** Extract commonly used utilities into a shared `types\u002Futils.ts` file.\n\n**Latest TypeScript Patterns:** Key remapping with `as` (TS 4.1+). Recursive conditional types.\n\n**Interview Tip:** Emphasize that custom utility types are the hallmark of advanced TypeScript. They reduce boilerplate and encode business logic at the type level.\n\n**Common Follow-up:** \"How do you create a `Writable\u003CT>` that removes `readonly` from all properties?\"\n\n**Real-world Example:** In a database ORM, `PickByType\u003CSchema, Date>` extracts all datetime columns for automatic conversion.",[238,516,517,518],"pick-by-type","merge","partial-by-keys",{"id":133,"category":520,"question":521,"answer":522,"level":404,"tags":523},"Type-Safe API Architecture","How do you design a type-safe API architecture using TypeScript, including shared types, contract validation, and automatic inference?","**Concept Explanation:** A type-safe API ensures that frontend and backend share the same types, request\u002Fresponse shapes are validated, and errors are typed. This is achieved by: defining shared schemas (Zod), generating TypeScript types from schemas, using a full-stack framework (tRPC, GraphQL Codegen), and validating at runtime on both ends.\n\n**Internal Behavior:** On the backend, route handlers are typed with request\u002Fresponse types. The frontend client uses the same types, often inferred from the backend (via code generation). Validation ensures that runtime data matches the types.\n\n**Syntax & Code Example (using tRPC):**\n```ts\n\u002F\u002F shared\u002Fschemas\u002Fuser.ts\nimport { z } from 'zod';\nexport const UserSchema = z.object({ id: z.number(), name: z.string() });\nexport type User = z.infer\u003Ctypeof UserSchema>;\n\n\u002F\u002F server\u002Frouter.ts\nimport { router, procedure } from '.\u002Ftrpc';\nexport const appRouter = router({\n  getUser: procedure.input(z.number()).query(async ({ input }) => {\n    return db.user.findUnique({ where: { id: input } }); \u002F\u002F returns User\n  }),\n});\nexport type AppRouter = typeof appRouter;\n\n\u002F\u002F client\u002Findex.ts\nimport { createTRPCReact } from '@trpc\u002Freact-query';\nconst trpc = createTRPCReact\u003CAppRouter>();\n\u002F\u002F usage: trpc.getUser.useQuery(1) returns typed User\n```\n\n**Alternative: OpenAPI + codegen**\n```yaml\n# openapi.yaml\npaths:\n  \u002Fusers\u002F{id}:\n    get:\n      responses:\n        200:\n          content:\n            application\u002Fjson:\n              schema:\n                $ref: '#\u002Fcomponents\u002Fschemas\u002FUser'\n```\nGenerate types with `openapi-typescript`.\n\n**Practical Example:** A monorepo with `packages\u002Fshared` containing Zod schemas, used by both `packages\u002Fserver` (for validation) and `packages\u002Fweb` (for type-safe calls).\n\n**Common Mistakes:** Not validating at runtime (trusting static types). Duplicating types across frontend\u002Fbackend (causes divergence).\n\n**Edge Cases:** File uploads, streaming responses, and WebSockets require special handling. Partial updates vs full updates.\n\n**Interview Follow-ups:** \"What is tRPC and how does it compare to GraphQL?\" \"How do you handle versioning in type-safe APIs?\"\n\n**Best Practices:** Use a single source of truth (Zod schema). Implement runtime validation at the boundary. Use code generation to keep types in sync.\n\n**Performance Considerations:** Validation overhead; cache compiled schemas. Use `fastify` with built-in JSON schema validation for high performance.\n\n**Production Recommendations:** For internal APIs, tRPC is excellent. For public APIs, OpenAPI + codegen is more interoperable.\n\n**Latest TypeScript Patterns:** `z.infer\u003Ctypeof schema>` for inferred types. `createRouter` from tRPC v10.\n\n**Interview Tip:** Emphasize that type-safe API architecture is critical for large teams, preventing mismatches that cause runtime errors.\n\n**Common Follow-up:** \"How do you handle authentication and authorization in a type-safe way?\"\n\n**Real-world Example:** A fintech app uses tRPC with Zod. The backend validates all inputs, and the frontend has full autocomplete for API calls. A change in the backend schema immediately types the frontend, preventing mismatches.",[394,79,524,396,525],"trpc","openapi",{"id":143,"category":527,"question":528,"answer":529,"level":404,"tags":530},"Monorepo Typing","What are monorepo typing strategies? How do project references, path mapping, and composite tsconfig work together?","**Concept Explanation:** In a monorepo, multiple packages share types. TypeScript project references (`composite`, `references`) allow incremental builds and cross-package type safety. Path mapping (`paths` in tsconfig) maps imports to source folders. Composite projects emit `.d.ts` files for dependent projects.\n\n**Internal Behavior:** When `composite` is enabled, TypeScript outputs `.d.ts` and `.tsbuildinfo` files. Project references tell the compiler to build dependencies first. The compiler tracks timestamps and only rebuilds changed projects.\n\n**Syntax & Code Example (monorepo structure):**\n```\npackages\u002F\n  core\u002F\n    tsconfig.json\n    src\u002Findex.ts\n  utils\u002F\n    tsconfig.json\n    src\u002Findex.ts\n  app\u002F\n    tsconfig.json\n    src\u002Fmain.ts\n```\n\n**tsconfig.json for core (composite):**\n```json\n{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"declaration\": true,\n    \"declarationMap\": true,\n    \"outDir\": \".\u002Fdist\",\n    \"rootDir\": \".\u002Fsrc\"\n  },\n  \"include\": [\"src\u002F**\u002F*\"]\n}\n```\n\n**tsconfig for app (references):**\n```json\n{\n  \"extends\": \"..\u002F..\u002Ftsconfig.base.json\",\n  \"references\": [\n    { \"path\": \"..\u002Fcore\" },\n    { \"path\": \"..\u002Futils\" }\n  ],\n  \"compilerOptions\": {\n    \"outDir\": \".\u002Fdist\"\n  }\n}\n```\n\n**Path mapping in base tsconfig:**\n```json\n{\n  \"compilerOptions\": {\n    \"paths\": {\n      \"@myorg\u002Fcore\": [\".\u002Fpackages\u002Fcore\u002Fsrc\"],\n      \"@myorg\u002Futils\": [\".\u002Fpackages\u002Futils\u002Fsrc\"]\n    }\n  }\n}\n```\n\n**Building:**\n```bash\ntsc --build packages\u002F**\u002Ftsconfig.json\n```\n\n**Practical Example:** A large monorepo with 10 packages. After changes in `core`, only `core` and its dependents (`app`) are rebuilt.\n\n**Common Mistakes:** Not setting `composite: true` in referenced projects. Using `paths` without `references` causing duplicate type instances.\n\n**Edge Cases:** Circular references are not allowed. `rootDir` and `outDir` must be set carefully for composite projects.\n\n**Interview Follow-ups:** \"How does `tsc --build` differ from `tsc`?\" \"What is the purpose of `tsbuildinfo` files?\"\n\n**Best Practices:** Use a single shared `tsconfig.base.json`. Enable `composite` for all packages. Use `incremental` for faster rebuilds.\n\n**Performance Considerations:** Project references speed up builds dramatically by avoiding re-checking unchanged dependencies.\n\n**Production Recommendations:** Use tools like Nx, Turborepo, or Rush for monorepo orchestration; they integrate with TypeScript project references.\n\n**Latest TypeScript Patterns:** `module: NodeNext` with project references works in Node.js monorepos.\n\n**Interview Tip:** Emphasize that monorepo typing is a scalable way to manage large codebases, preventing circular dependencies and improving build times.\n\n**Common Follow-up:** \"How do you handle `node_modules` in a monorepo?\"\n\n**Real-world Example:** A company with 50 internal npm packages migrated to project references, reducing CI build time from 15 minutes to 3 minutes.",[470,471,531,532],"composite","paths",{"id":153,"category":534,"question":535,"answer":536,"level":404,"tags":537},"Advanced React Typing","How do you type advanced React patterns like higher-order components (HOC), generic components, and polymorphic components with TypeScript?","**Concept Explanation:** Advanced React typing includes: HOCs that enhance components while preserving props; generic components that work with any data type; polymorphic components (e.g., `\u003CButton as=\"a\" href=\"...\"\u002F>`). These require careful use of `React.ComponentProps`, `Omit`, `PropsWithChildren`, and generic constraints.\n\n**Internal Behavior:** HOCs use function overloads or conditional types to return a component with modified props. Generic components use type parameters on the function component. Polymorphic components use a generic `As` type parameter and `ComponentPropsWithRef`.\n\n**Syntax & Code Example:**\n```tsx\n\u002F\u002F Higher-Order Component typing\nfunction withLoading\u003CP extends { isLoading?: boolean }>(\n  Component: React.ComponentType\u003CP>\n): React.ComponentType\u003COmit\u003CP, 'isLoading'>> {\n  return function WrappedComponent(props: Omit\u003CP, 'isLoading'>) {\n    \u002F\u002F ... loading logic\n    return \u003CComponent {...(props as P)} isLoading={loading} \u002F>;\n  };\n}\n\n\u002F\u002F Generic component\ninterface ListProps\u003CT> {\n  items: T[];\n  renderItem: (item: T) => React.ReactNode;\n}\nfunction List\u003CT>({ items, renderItem }: ListProps\u003CT>) {\n  return \u003Cdiv>{items.map(renderItem)}\u003C\u002Fdiv>;\n}\n\u002F\u002F Usage: \u003CList items={[1,2,3]} renderItem={item => \u003Cspan>{item}\u003C\u002Fspan>} \u002F>\n\n\u002F\u002F Polymorphic component\ntype AsProp\u003CE extends React.ElementType = 'div'> = { as?: E };\ntype PolymorphicProps\u003CE extends React.ElementType, P = {}> = P & AsProp\u003CE> & Omit\u003CReact.ComponentProps\u003CE>, keyof (P & AsProp\u003CE>)>;\nfunction PolymorphicButton\u003CE extends React.ElementType = 'button'>({\n  as,\n  children,\n  ...props\n}: PolymorphicProps\u003CE, { children: React.ReactNode }>) {\n  const Component = as || 'button';\n  return \u003CComponent {...props}>{children}\u003C\u002FComponent>;\n}\n```\n\n**Practical Example:** A `Link` component that can render as `\u003Ca>` or React Router `\u003CLink>` using polymorphic typing.\n\n**Common Mistakes:** HOC losing refs (use `forwardRef`). Generic components causing unnecessary re-renders (use `React.memo` with generics carefully).\n\n**Edge Cases:** `React.forwardRef` with generic components requires two overloads.\n\n**Interview Follow-ups:** \"How do you type `forwardRef` with generics?\" \"What is the `ComponentPropsWithoutRef` utility?\"\n\n**Best Practices:** Use `React.ElementType` for as-prop. Use `ComponentPropsWithRef` for polymorphic components. Document generic constraints.\n\n**Performance Considerations:** Generics are compile-time only; no runtime cost.\n\n**Production Recommendations:** For polymorphic components, provide a default `as` constraint. Use `satisfies` to ensure proper props.\n\n**Latest TypeScript Patterns:** `React.forwardRef` now works better with generic components (TypeScript 5.0+).\n\n**Interview Tip:** Emphasize that advanced typing of components makes libraries more reusable and type-safe, a mark of senior React developers.\n\n**Common Follow-up:** \"How do you type a component that accepts render props?\"\n\n**Real-world Example:** In a design system, the `Box` component is polymorphic (`as=\"div\"`, `as=\"section\"`, etc.) and properly inherits all native props of the rendered element, with TypeScript enforcing correct attributes.",[334,538,539,540,541],"hoc","generic-components","polymorphic","forwardRef",{"id":164,"category":543,"question":544,"answer":545,"level":404,"tags":546},"Advanced Vue Typing","How do you type advanced Vue 3 patterns: generic components, composables, provide\u002Finject, and slots with TypeScript?","**Concept Explanation:** Vue 3 Composition API provides excellent TypeScript integration. Generic components are supported with `defineComponent` and `setup` generic. Provide\u002Finject requires typed injection keys using `InjectionKey`. Slots can be typed using `defineSlots` (Vue 3.3+). Composables are typed like functions, often returning reactive refs.\n\n**Internal Behavior:** `defineProps` accepts a type literal. `defineEmits` uses call signature. `defineComponent` infers types from `setup` return. `InjectionKey\u003CT>` ensures provide and inject share the same type.\n\n**Syntax & Code Example:**\n```vue\n\u003C!-- Generic component List.vue -->\n\u003Cscript setup lang=\"ts\" generic=\"T\">\ndefineProps\u003C{\n  items: T[];\n  renderItem: (item: T) => any;\n}>();\n\u003C\u002Fscript>\n\n\u003C!-- Provide\u002FInject with typed key -->\n\u003Cscript lang=\"ts\">\nimport { InjectionKey } from 'vue';\ninterface User { name: string; }\nexport const userKey: InjectionKey\u003CUser> = Symbol('user');\n\u003C\u002Fscript>\n\u003Cscript setup>\nimport { provide, inject } from 'vue';\nprovide(userKey, { name: 'Alice' });\n\nconst user = inject(userKey); \u002F\u002F user: User | undefined\n\u003C\u002Fscript>\n\n\u003C!-- Typed slots (Vue 3.3+) -->\n\u003Cscript setup lang=\"ts\">\ndefineSlots\u003C{\n  header(props: { title: string }): any;\n  default(): any;\n}>();\n\u003C\u002Fscript>\n\n\u003C!-- Composables -->\n\u002F\u002F composables\u002FuseCounter.ts\nexport function useCounter(initial = 0) {\n  const count = ref(initial);\n  const increment = () => count.value++;\n  return { count, increment };\n}\n\u002F\u002F In component, const { count, increment } = useCounter();\n```\n\n**Practical Example:** A `DataTable` generic component that accepts `items` of any type and `columns` definition with typed accessors.\n\n**Common Mistakes:** Not using `InjectionKey` leads to `unknown` type. Generic components require `generic` attribute in `script setup`.\n\n**Edge Cases:** Vue 3.2 and earlier lack generic component support (use `defineComponent` instead).\n\n**Interview Follow-ups:** \"How do you type Vuex mutations?\" \"What is `Context` in setup props?\"\n\n**Best Practices:** Use `InjectionKey\u003CT>` for typed provide\u002Finject. Use `Generic` attribute for component generics. Prefer `defineProps\u003CType>()` over runtime validation when possible.\n\n**Performance Considerations:** Types are erased, no runtime cost.\n\n**Production Recommendations:** Enable `vue-tsc` for type checking. Use `strict` mode.\n\n**Latest TypeScript Patterns:** `defineSlots` and `generic` are stable in Vue 3.3+. `defineModel` macro for v-model typing.\n\n**Interview Tip:** Emphasize that Vue's TypeScript support is mature, especially with Composition API. Generic components and typed slots are game-changers for reusable libraries.\n\n**Common Follow-up:** \"How do you type a Vue composable that uses `provide` internally?\"\n\n**Real-world Example:** A table component that accepts `columns` array with typed keys: `columns: { key: keyof T, title: string }[]` – the component ensures the `key` exists on the data type.",[344,539,547,548,346],"provide-inject","slots",{"id":174,"category":550,"question":551,"answer":552,"level":404,"tags":553},"Advanced Nuxt Typing","How do you leverage TypeScript in Nuxt 3 for typing auto-imports, pages, middleware, and modules?","**Concept Explanation:** Nuxt 3 generates TypeScript types for auto-imported components, composables, pages, layouts, and middleware. You can augment `NuxtConfig`, `NuxtApp`, and `RuntimeConfig` using declaration merging. Custom modules can export types. Auto-imported composables from `composables\u002F` are fully typed.\n\n**Internal Behavior:** Nuxt generates `.nuxt\u002Ftsconfig.json` and `.nuxt\u002Ftypes` with inferred types. It uses `unplugin-auto-import` to generate declarations. Pages get route param types from file-based routing.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F ~\u002Ftypes\u002Fnuxt.d.ts – augmenting NuxtApp\ndeclare module '#app' {\n  interface NuxtApp {\n    $api: {\n      fetchUser(id: number): Promise\u003CUser>;\n    };\n  }\n}\ndeclare module 'nuxt\u002Fschema' {\n  interface RuntimeConfig {\n    public: { apiBase: string; };\n    secretKey: string;\n  }\n}\n\n\u002F\u002F pages\u002Fusers\u002F[id].vue – typed route params\n\u003Cscript setup lang=\"ts\">\nconst route = useRoute();\nconst { id } = route.params; \u002F\u002F string | string[]\n\u002F\u002F Define validation to narrow type\ndefinePageMeta({\n  validate: (route) => \u002F^\\d+$\u002F.test(route.params.id as string),\n});\n\n\u002F\u002F composables\u002FuseApi.ts – auto-imported and typed\nexport const useApi = () => {\n  const config = useRuntimeConfig();\n  const $fetch = useNuxtApp().$fetch;\n  return { config };\n};\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A custom Nuxt module that adds a typed `$auth` property to NuxtApp, with full autocompletion in components.\n\n**Common Mistakes:** Not generating types after adding files (Nuxt does automatically). Over-augmenting without proper module declaration.\n\n**Edge Cases:** Page param types are not automatically union of possible values; you must use `validate` to narrow.\n\n**Interview Follow-ups:** \"How do you type custom `definePageMeta` properties?\" \"How do you create a typed plugin?\"\n\n**Best Practices:** Use `nuxi typecheck` in CI. Extend `RuntimeConfig` in a dedicated `.d.ts` file. Prefer auto-imports over manual imports.\n\n**Performance Considerations:** Type generation adds build time but no runtime cost.\n\n**Production Recommendations:** Enable `strict` in `tsconfig.json`. Use `vue-tsc` to type-check templates.\n\n**Latest TypeScript Patterns:** `defineNuxtPlugin` returns a typed provide object. `defineNuxtConfig` is fully typed.\n\n**Interview Tip:** Emphasize that Nuxt 3's TypeScript is a major selling point; it's seamless and powerful for full-stack typing.\n\n**Common Follow-up:** \"How do you type custom middleware?\"\n\n**Real-world Example:** In a Nuxt app with dynamic routes, definePageMeta validation narrows `route.params.id` to `string` (instead of `string | string[]`), enabling type-safe API calls.",[352,353,554,277],"runtime-config",{"id":184,"category":556,"question":557,"answer":558,"level":404,"tags":559},"Type-Safe State Management","How do you implement type-safe state management with Zustand (or Redux Toolkit) using TypeScript, including middleware and slices?","**Concept Explanation:** Zustand and Redux Toolkit provide TypeScript integration for type-safe global state. Store definitions include state and action types. Slices (Redux Toolkit) or store creators (Zustand) infer types from the definitions. Middleware can be typed generically.\n\n**Internal Behavior:** Zustand's `create` function infers the store type from the initial state and actions. Redux Toolkit's `createSlice` infers the state and actions, and `combineReducers` creates a typed root reducer.\n\n**Syntax & Code Example (Zustand):**\n```ts\nimport { create } from 'zustand';\n\ninterface BearState {\n  bears: number;\n  increase: (by: number) => void;\n  reset: () => void;\n}\n\nconst useBearStore = create\u003CBearState>((set) => ({\n  bears: 0,\n  increase: (by) => set((state) => ({ bears: state.bears + by })),\n  reset: () => set({ bears: 0 }),\n}));\n\n\u002F\u002F Usage: const bears = useBearStore((state) => state.bears);\n```\n\n**Redux Toolkit with slices:**\n```ts\nimport { configureStore, createSlice, PayloadAction } from '@reduxjs\u002Ftoolkit';\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: { value: 0 },\n  reducers: {\n    increment: (state) => { state.value += 1; },\n    decrement: (state) => { state.value -= 1; },\n    incrementByAmount: (state, action: PayloadAction\u003Cnumber>) => {\n      state.value += action.payload;\n    },\n  },\n});\n\nexport const store = configureStore({\n  reducer: { counter: counterSlice.reducer },\n});\nexport type RootState = ReturnType\u003Ctypeof store.getState>;\nexport type AppDispatch = typeof store.dispatch;\n\n\u002F\u002F Typed hooks (useAppDispatch, useAppSelector)\nconst useAppDispatch = () => useDispatch\u003CAppDispatch>();\nconst useAppSelector: TypedUseSelectorHook\u003CRootState> = useSelector;\n```\n\n**Practical Example:** A todo store with typed actions for add, toggle, remove, and filter by status.\n\n**Common Mistakes:** Forgetting to export `RootState` and `AppDispatch`. Using `any` in middleware or selectors.\n\n**Edge Cases:** Async actions (Redux Thunk) need `AsyncThunk` types or `createAsyncThunk`.\n\n**Interview Follow-ups:** \"How do you type Redux middleware?\" \"What is the difference between Zustand and Redux Toolkit typing?\"\n\n**Best Practices:** Use `zustand` for simpler typing, Redux Toolkit for complex apps. Always export `RootState` and typed hooks.\n\n**Performance Considerations:** No runtime overhead; types only.\n\n**Production Recommendations:** Use `reselect` for memoized selectors with proper typing.\n\n**Latest TypeScript Patterns:** Zustand's `create` with `zustand\u002Fmiddleware` supports persist, devtools, etc., all typed.\n\n**Interview Tip:** Emphasize that type-safe state management prevents entire classes of bugs (e.g., misspelled action types, mismatched payloads).\n\n**Common Follow-up:** \"How do you handle side effects in a type-safe way?\" (Use `zustand` middleware or Redux Toolkit middleware)\n\n**Real-world Example:** A shopping cart store with Zustand. The store has typed actions (`addItem`, `removeItem`, `clearCart`), and React components use selectors to compute totals. TypeScript ensures that cart items match the `Product` type.",[560,561,562,563,564],"zustand","redux","state-management","slices","dispatch",{"id":195,"category":566,"question":567,"answer":568,"level":404,"tags":569},"Enterprise TypeScript Architecture","How do you structure a large-scale TypeScript application with layered architecture (domain, application, infrastructure, presentation)?","**Concept Explanation:** Large TypeScript apps benefit from layered architecture: **Domain**: core business types and logic (pure TS, no external deps). **Application**: use cases, services orchestrating domain. **Infrastructure**: external dependencies (database, API, file system). **Presentation**: UI components (React\u002FVue). Each layer has its own types, and dependencies point inward (presentation -> application -> domain \u003C- infrastructure).\n\n**Internal Behavior:** TypeScript enforces layer boundaries via `paths` mapping and `tsconfig` project references. Domain layer has no imports from other layers. Infrastructure implements interfaces defined in application\u002Fdomain.\n\n**Syntax & Code Example (folder structure):**\n```\nsrc\u002F\n  domain\u002F\n    user\u002F\n      User.ts (interface)\n      UserRepository.ts (interface)\n      UserService.ts (business logic)\n  application\u002F\n    user\u002F\n      GetUserUseCase.ts (uses domain)\n      CreateUserCommand.ts\n  infrastructure\u002F\n    user\u002F\n      PrismaUserRepository.ts (implements UserRepository)\n    db\u002F\n      prismaClient.ts\n  presentation\u002F\n    components\u002F\n      UserProfile.tsx\n    pages\u002F\n      users\u002F[id].tsx\n  shared\u002F\n    utils\u002F\n    types\u002F\n```\n\n**Typed dependency injection using interfaces:**\n```ts\n\u002F\u002F domain\u002Fuser\u002FUserRepository.ts\nexport interface UserRepository {\n  findById(id: string): Promise\u003CUser | null>;\n  save(user: User): Promise\u003Cvoid>;\n}\n\n\u002F\u002F infrastructure\u002Fuser\u002FPrismaUserRepository.ts\nimport { UserRepository } from '..\u002F..\u002Fdomain\u002Fuser\u002FUserRepository';\nexport class PrismaUserRepository implements UserRepository {\n  async findById(id: string) { \u002F* prisma call *\u002F }\n}\n\n\u002F\u002F application\u002Fuser\u002FGetUserUseCase.ts\nexport class GetUserUseCase {\n  constructor(private userRepository: UserRepository) {}\n  async execute(id: string): Promise\u003CUser> { \u002F* use repo *\u002F }\n}\n\n\u002F\u002F presentation – composition root\nconst userRepo = new PrismaUserRepository();\nconst getUserUseCase = new GetUserUseCase(userRepo);\n```\n\n**Practical Example:** An e-commerce system with domain (Product, Order, Customer), application (PlaceOrderUseCase), infrastructure (StripePaymentGateway, PostgresOrderRepository), and presentation (React checkout form).\n\n**Common Mistakes:** Domain depending on infrastructure (e.g., importing Prisma types). Circular dependencies between layers.\n\n**Edge Cases:** Shared types (DTOs) between layers go into `shared\u002Ftypes`. Testing uses mocks implementing interfaces.\n\n**Interview Follow-ups:** \"How do you handle DTOs and entities?\" \"What is the role of `tsconfig` paths in enforcing boundaries?\"\n\n**Best Practices:** Use `paths` in tsconfig to alias layers (`@domain\u002F*`, `@infrastructure\u002F*`). Use `project references` to enforce build order.\n\n**Performance Considerations:** No runtime cost; types are erased.\n\n**Production Recommendations:** Use `Nx` or `turbo` for monorepo to enforce boundaries via lint rules (`@nrwl\u002Fnx\u002Fenforce-module-boundaries`).\n\n**Latest TypeScript Patterns:** `exports` in package.json for private packages. `verbatimModuleSyntax` for cleaner imports.\n\n**Interview Tip:** Emphasize that enterprise architecture is about managing complexity. TypeScript's structural typing and modules help enforce clean boundaries.\n\n**Common Follow-up:** \"How do you handle dependency injection in TypeScript?\" (Use interfaces and composition root, not decorators)\n\n**Real-world Example:** A fintech company migrated a 200k LOC codebase to layered architecture, reducing coupling and enabling independent team work. New features are added without fear of breaking unrelated modules.",[570,571,572,573,574],"architecture","ddd","layers","dependency-injection","enterprise",{"id":203,"category":576,"question":577,"answer":578,"level":404,"tags":579},"Scalable Typing Patterns","What are scalable typing patterns for large codebases? Discuss opaque types, fluent interfaces, builder pattern, and smart constructors.","**Concept Explanation:** Scalable typing patterns help manage complexity in large codebases: **Opaque types** (branded) prevent primitive obsession. **Fluent interfaces** return `this` for chaining. **Builder pattern** constructs complex objects step by step. **Smart constructors** (static factory methods) validate inputs before creating objects.\n\n**Internal Behavior:** These patterns leverage TypeScript's structural typing, branded types, and class method chaining. They push validation and invariants to the type system where possible.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Branded types (opaque)\ntype NonEmptyString = string & { __brand: 'NonEmptyString' };\nfunction createNonEmptyString(s: string): NonEmptyString {\n  if (s.length === 0) throw new Error('String cannot be empty');\n  return s as NonEmptyString;\n}\n\n\u002F\u002F Fluent interface\nclass QueryBuilder {\n  private selectClause: string[] = [];\n  private fromClause: string = '';\n  select(...fields: string[]): this {\n    this.selectClause = fields;\n    return this;\n  }\n  from(table: string): this {\n    this.fromClause = table;\n    return this;\n  }\n  build(): string {\n    return `SELECT ${this.selectClause.join(', ')} FROM ${this.fromClause}`;\n  }\n}\n\n\u002F\u002F Builder pattern with fluent interface\nclass UserBuilder {\n  private user: Partial\u003CUser> = {};\n  setName(name: string): this {\n    this.user.name = name;\n    return this;\n  }\n  setEmail(email: string): this {\n    this.user.email = email;\n    return this;\n  }\n  build(): User {\n    if (!this.user.name) throw new Error('Name required');\n    return this.user as User;\n  }\n}\n\n\u002F\u002F Smart constructor\nclass Email {\n  private constructor(private value: string) {}\n  static create(email: string): Email {\n    if (!email.includes('@')) throw new Error('Invalid email');\n    return new Email(email);\n  }\n  getValue(): string { return this.value; }\n}\n```\n\n**Practical Example:** In a banking app, `AccountNumber` is an opaque type. A `TransactionBuilder` ensures all required fields are set before building.\n\n**Common Mistakes:** Over-engineering with complex types. Not using branded types for primitive validation.\n\n**Edge Cases:** Fluent interfaces with async methods need return type `Promise\u003Cthis>`.\n\n**Interview Follow-ups:** \"How do you combine builder pattern with readonly types?\" \"What is the advantage of smart constructors?\"\n\n**Best Practices:** Use opaque types for IDs, email, phone numbers. Use builder pattern for objects with many optional fields.\n\n**Performance Considerations:** No runtime overhead; patterns are compile-time or minimal runtime.\n\n**Production Recommendations:** Export smart constructors as the only way to create domain objects, ensuring invariants hold.\n\n**Latest TypeScript Patterns:** `satisfies` with builders for type inference.\n\n**Interview Tip:** Emphasize that these patterns reduce cognitive load and prevent bugs at the type level, essential for large teams.\n\n**Common Follow-up:** \"How does the builder pattern differ from the factory pattern?\"\n\n**Real-world Example:** A configuration library uses a fluent builder for creating HTTP clients: `new ClientBuilder().baseUrl('https:\u002F\u002Fapi.com').withTimeout(5000).withRetry(3).build()` – TypeScript enforces mandatory fields at the type level.",[580,581,582,583,440],"patterns","fluent","builder","smart-constructors",{"id":585,"category":586,"question":587,"answer":588,"level":404,"tags":589},24,"Advanced Type Guards","How do you build complex type guards for union discrimination, array element validation, and object shape checks?","**Concept Explanation:** Advanced type guards go beyond `typeof` and `instanceof`. They include checking for discriminated unions using `in` operator, validating array elements recursively, and checking complex object shapes. User-defined type guards with `value is Type` allow narrowing in custom ways.\n\n**Internal Behavior:** TypeScript uses control flow analysis. When you return a type predicate (`value is Type`), the compiler narrows the variable's type in the true branch. Guards can be generic.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F Discriminated union guard\ninterface Square { kind: 'square'; size: number; }\ninterface Circle { kind: 'circle'; radius: number; }\ntype Shape = Square | Circle;\nfunction isSquare(shape: Shape): shape is Square {\n  return shape.kind === 'square';\n}\n\n\u002F\u002F Array element validation\ntype NonEmptyArray\u003CT> = [T, ...T[]];\nfunction isNonEmpty\u003CT>(arr: T[]): arr is NonEmptyArray\u003CT> {\n  return arr.length > 0;\n}\n\n\u002F\u002F Object shape guard (checking property types)\nfunction isUser(obj: any): obj is { id: number; name: string } {\n  return obj && typeof obj.id === 'number' && typeof obj.name === 'string';\n}\n\n\u002F\u002F Generic guard for key existence\nfunction hasKey\u003CT extends object, K extends string>(obj: T, key: K): obj is T & Record\u003CK, unknown> {\n  return key in obj;\n}\n\n\u002F\u002F Recursive guard for deep validation\ntype JsonValue = string | number | boolean | null | JsonObject | JsonArray;\ninterface JsonObject { [key: string]: JsonValue; }\ninterface JsonArray extends Array\u003CJsonValue> {}\nfunction isJsonValue(value: unknown): value is JsonValue {\n  if (value === null) return true;\n  if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return true;\n  if (Array.isArray(value)) return value.every(isJsonValue);\n  if (typeof value === 'object') return Object.values(value).every(isJsonValue);\n  return false;\n}\n```\n\n**Practical Example:** Validating API response data: `if (isUser(data)) { setUser(data); } else { handleError(); }`.\n\n**Common Mistakes:** Not handling `null` or `undefined` in guards. Overly permissive guards that don't actually narrow.\n\n**Edge Cases:** Guards that check optional properties: use `'prop' in obj` to distinguish absence vs undefined.\n\n**Interview Follow-ups:** \"How do you create a guard for a union type with a shared property?\" \"What is the difference between `is` and `asserts`?\"\n\n**Best Practices:** Keep type guards pure (no side effects). Test them thoroughly. Use `asserts` for validation functions that throw.\n\n**Performance Considerations:** Runtime checks; balance thoroughness with speed.\n\n**Production Recommendations:** Use Zod for complex validation, but type guards for simple, performance-critical checks.\n\n**Latest TypeScript Patterns:** `satisfies` with type guards. `infer` in conditional types can derive guard types.\n\n**Interview Tip:** Emphasize that type guards bridge the gap between runtime and compile-time types, essential for parsing external data.\n\n**Common Follow-up:** \"How do you write a type guard for a union of functions?\"\n\n**Real-world Example:** A WebSocket message handler uses a discriminated union guard (`isLoginMessage`, `isDataMessage`) to route messages and narrow the type for each case.",[253,590,114,591],"validation","predicate",{"id":593,"category":594,"question":595,"answer":596,"level":404,"tags":597},25,"TypeScript & AST","How do you use the TypeScript Compiler API to manipulate AST, create custom transformations, or build a code generator?","**Concept Explanation:** The TypeScript Compiler API allows programmatic access to the AST, type system, and emitter. You can parse source files, traverse nodes, transform code, or generate new code. Common use cases: custom linters, codemods, documentation generators, and framework compilers.\n\n**Internal Behavior:** The API exposes factories, transformers, and printers. You create a `Program`, get `SourceFile`, traverse with `forEachChild`, modify nodes with `transformer` function, and emit with `Printer`.\n\n**Syntax & Code Example:**\n```ts\nimport ts from 'typescript';\n\n\u002F\u002F Parse a file\nconst program = ts.createProgram(['input.ts'], {\n  target: ts.ScriptTarget.ES2020,\n});\nconst sourceFile = program.getSourceFile('input.ts');\n\n\u002F\u002F Traverse and find all function declarations\nfunction visit(node: ts.Node) {\n  if (ts.isFunctionDeclaration(node) && node.name) {\n    console.log(`Found function: ${node.name.text}`);\n  }\n  ts.forEachChild(node, visit);\n}\nvisit(sourceFile);\n\n\u002F\u002F Create a transformer that wraps function bodies with a logger\nconst transformer = (context: ts.TransformationContext) => (rootNode: ts.SourceFile) => {\n  function visit(node: ts.Node): ts.Node {\n    if (ts.isFunctionDeclaration(node) && node.body) {\n      const newBody = ts.factory.createBlock([\n        ts.factory.createExpressionStatement(\n          ts.factory.createCallExpression(\n            ts.factory.createIdentifier('console.log'),\n            undefined,\n            [ts.factory.createStringLiteral(`Entering ${node.name?.text}`)]\n          )\n        ),\n        ...node.body.statements,\n      ], true);\n      return ts.factory.updateFunctionDeclaration(\n        node, node.modifiers, node.asteriskToken, node.name,\n        node.typeParameters, node.parameters, node.type, newBody\n      );\n    }\n    return ts.visitEachChild(node, visit, context);\n  }\n  return ts.visitNode(rootNode, visit);\n};\n\n\u002F\u002F Custom code generator\nconst result = ts.createSourceFile('output.ts', '', ts.ScriptTarget.ESNext);\nconst printer = ts.createPrinter();\nconst code = printer.printNode(ts.EmitHint.Unspecified, ts.factory.createVariableStatement(\n  undefined,\n  ts.factory.createVariableDeclarationList([\n    ts.factory.createVariableDeclaration('x', undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), ts.factory.createNumericLiteral(42))\n  ], ts.NodeFlags.Const)\n), result);\n```\n\n**Practical Example:** A codemod that renames a prop in all React components across a codebase.\n\n**Common Mistakes:** Not handling whitespace and comments (they are lost). Mutating nodes incorrectly (need to create new ones).\n\n**Edge Cases:** TypeScript's internal APIs may change between versions. Use `ts.version` for compatibility.\n\n**Interview Follow-ups:** \"What is the difference between `createProgram` and `createLanguageService`?\" \"How do you handle source maps?\"\n\n**Best Practices:** Use `ts.forEachChild` for traversal. Use `ts.factory` to create nodes. Test with `ts.createPrinter`.\n\n**Performance Considerations:** Compiler API can be slow; reuse `Program` and `TypeChecker`.\n\n**Production Recommendations:** For production tools, consider using `ts-morph` (higher-level wrapper) for simpler code.\n\n**Latest TypeScript Patterns:** `ts.createSourceFile` with `ScriptTarget`. `ts.transform` API.\n\n**Interview Tip:** Emphasize that mastering the Compiler API opens doors to advanced tooling – linters, formatters, and framework compilers (like Angular, Svelte).\n\n**Common Follow-up:** \"How would you build a plugin system for TypeScript?\"\n\n**Real-world Example:** The `typescript-eslint` parser uses the Compiler API to parse TypeScript and generate AST compatible with ESLint.",[598,507,599,600,601],"compiler-api","transformer","code-generation","codemod",1779734543422]