{"id":22814291,"url":"https://github.com/devinterview-io/typescript-interview-questions","last_synced_at":"2025-10-03T23:59:37.541Z","repository":{"id":108758203,"uuid":"326952536","full_name":"Devinterview-io/typescript-interview-questions","owner":"Devinterview-io","description":"🟣 Typescript interview questions and answers to help you prepare for your next technical interview in 2025.","archived":false,"fork":false,"pushed_at":"2025-07-29T14:16:51.000Z","size":51,"stargazers_count":135,"open_issues_count":1,"forks_count":36,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-03T23:59:37.345Z","etag":null,"topics":["coding-interview-questions","coding-interviews","interview-practice","interview-prep","interview-preparation","leetcode-questions","leetcode-solutions","programming-interview-questions","software-developer-interview","software-engineer-interview","software-engineering","technical-interview-questions","typescript","typescript-interview-questions","typescript-questions","typescript-tech-interview","web-and-mobile-development-interview-questions"],"latest_commit_sha":null,"homepage":"https://devinterview.io/","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Devinterview-io.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2021-01-05T09:41:32.000Z","updated_at":"2025-09-30T08:35:09.000Z","dependencies_parsed_at":"2025-04-22T18:41:12.217Z","dependency_job_id":"2f688f6c-761d-43ba-b368-42997d4a6ae2","html_url":"https://github.com/Devinterview-io/typescript-interview-questions","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Devinterview-io/typescript-interview-questions","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Ftypescript-interview-questions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Ftypescript-interview-questions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Ftypescript-interview-questions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Ftypescript-interview-questions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Devinterview-io","download_url":"https://codeload.github.com/Devinterview-io/typescript-interview-questions/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Ftypescript-interview-questions/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":278245393,"owners_count":25955016,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-03T02:00:06.070Z","response_time":53,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["coding-interview-questions","coding-interviews","interview-practice","interview-prep","interview-preparation","leetcode-questions","leetcode-solutions","programming-interview-questions","software-developer-interview","software-engineer-interview","software-engineering","technical-interview-questions","typescript","typescript-interview-questions","typescript-questions","typescript-tech-interview","web-and-mobile-development-interview-questions"],"created_at":"2024-12-12T13:08:00.040Z","updated_at":"2025-10-03T23:59:37.534Z","avatar_url":"https://github.com/Devinterview-io.png","language":null,"readme":"# Top 100 Typescript Interview Questions in 2025\n\n\u003cdiv\u003e\n\u003cp align=\"center\"\u003e\n\u003ca href=\"https://devinterview.io/questions/web-and-mobile-development/\"\u003e\n\u003cimg src=\"https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/github-blog-img%2Fweb-and-mobile-development-github-img.jpg?alt=media\u0026token=1b5eeecc-c9fb-49f5-9e03-50cf2e309555\" alt=\"web-and-mobile-development\" width=\"100%\"\u003e\n\u003c/a\u003e\n\u003c/p\u003e\n\n#### You can also find all 100 answers here 👉 [Devinterview.io - Typescript](https://devinterview.io/questions/web-and-mobile-development/typescript-interview-questions)\n\n\u003cbr\u003e\n\n## 1. What is _TypeScript_ and how does it differ from _JavaScript_?\n\n**TypeScript** is a statically-typed superset of **JavaScript**, developed and maintained by Microsoft. It enables enhanced code maintainability and predictability. After compiling, TypeScript code is transpiled into standard, browser-compatible JavaScript.\n\nKey distinctions between TypeScript and JavaScript include the use of type annotations, the ability to work with existing JavaScript code, and more.\n\n### TypeScript Features \u0026 Benefits\n\n- **Type System**: Offers static typing, allowing developers to define the type of variables, parameters, and return values. This helps catch errors during development, reducing runtime issues.\n\n- **Advanced Language Features**: Incorporates modern ECMAScript syntax and features, often before they are rolled out in JavaScript. Additionally, TypeScript brings functional programming patterns, classes, and access modifiers (such as `public` and `private`)\n\n- **Compatibility with JavaScript**: TypeScript can interpret existing JavaScript code with minor or no modifications.\n\n- **Tooling and Extra Safety**: Provides enhanced autocompletion, refactoring, and documentation via TypeScript-aware tools. TypeScript helps catch and rectify common programming errors without needing to run the code.\n\n- **ECMAScript Compatibility**: TypeScript allows developers to target different **ECMAScript versions**, ensuring the generated JavaScript is compatible with the targeted browsers.\n\n- **Code Structure \u0026 Readability**: Promotes maintainability by enforcing a defined coding structure and fostering code clarity.\n\n### TypeScript's Role in Modern Development\n\n- **Workplace Adaptability**: TypeScript is used in an extensive range of projects, from small utilities to large-scale applications.\n\n- **Community Support**: Supported by a vibrant developer community, TypeScript benefits from frequent updates, bug fixes, and useful extensions.\n\n- **On-Going Development**: A robust language server furnishes accurate tooling feedback, such as linting and error suggestions in real time.\n\n- **Rapid Enhancement**: The TypeScript team consistently introduces new features and reinforces existing ones.\n\u003cbr\u003e\n\n## 2. Can you explain what is meant by \"_TypeScript_ is a _superset_ of _JavaScript_\"?\n\n**TypeScript** is often described as a **\"superset of JavaScript\"** because every valid JavaScript code is also a valid TypeScript code.\n\nTypeScript is designed in a way that it fully embraces existing **JavaScript syntax** and functionality. This ensures a smooth transition for developers wishing to adopt or migrate to TypeScript.\n\n### Key TypeScript Features On Top of JavaScript\n\n- **Type Definitions**: TypeScript introduces static typing through type annotations. These are optional, enabling gradual adoption for existing codebases that might not need them.\n\n- **Newer JavaScript Features**: TypeScript extends JavaScript syntax, providing support for the latest ECMAScript standards more effectively through its compiler, even when the underlying JavaScript engine might not support them yet.\n\n- **Tooling and Error Detection**: TypeScript offers robust type-checking, increased code readability, and stronger compile-time error detection.\n\n### Code Demonstration\n\nHere is the TypeScript code:\n\n```typescript\nlet num: number = 5;\nnum = \"this will raise a type error\";\n```\n\u003cbr\u003e\n\n## 3. What are the _basic types_ available in _TypeScript_?\n\n**TypeScript** provides an assortment of basic types for different kinds of data, such as numbers, strings, boolean values, arrays, tuples and more.\n\n### Common Basic Types in TypeScript\n\n- **Boolean**: Represents true/false values.\n\n- **Number**: Applies to both integer and floating-point numbers.\n\n- **String**: Refers to textual data.\n\n- **Array**: Offers a flexible way to work with structured data.\n\n- **Tuple**: Enables the definition of arrays with a fixed number of elements, each potentially of a different data type.\n\n- **Enum**: Provides a set of named constants such as days or colors.\n\n- **Any**: Offers a dynamic type, which can be used to bypass type-checking. It's typically best to be avoided, as it defeats the purpose of using TypeScript, which is primarily focused on static typing. However, there are certain use cases where it becomes necessary.\n\n- **Void**: Typically used as the return type for functions that don't return a value.\n\n- **Null** and **Undefined**: Allow for the assignment of null and undefined values, respectively. However, this isn’t enabled by default, and these are probably better handled using the `strict` mode settings in TypeScript.\n\n- **Never**: Represents the type of values that never occur. For instance, the return type of a function that doesn't reach its end or always throws an error.\n\n- **Object**: Any JavaScript object.\n\n- **Function**: Denotes a function type.\n\n### Code Example: Basic TypeScript Types\n\nHere is the TypeScript code:\n\n```typescript\n// Boolean\nlet isActive: boolean = true;\n\n// Number\nlet age: number = 30;\n\n// String\nlet title: string = \"Manager\";\n\n// Array\nlet scores: number[] = [85, 90, 78];\n// or use a compact form: let scores: Array\u003cnumber\u003e = [85, 90, 78];\n\n// Tuple\nlet employee: [string, number, boolean] = ['John', 35, true];\n\n// Enum\nenum WeekDays { Monday, Tuesday, Wednesday, Thursday, Friday }\nlet today: WeekDays = WeekDays.Wednesday;\n\n// Any\nlet dynamicData: any = 20;\n\n// Void\nfunction greet(): void {\n  console.log(\"Hello!\");\n}\n\n// Null and Undefined\nlet data: null = null;\nlet user: undefined = undefined;\n\n// Never\nfunction errorMessage(message: string): never {\n  throw new Error(message);\n}\n\n// Object\nlet person: object = {\n  name: 'John',\n  age: 30\n};\n\n// Function\nlet calculate: Function;\ncalculate = function (x: number, y: number): number {\n  return x + y;\n};\n```\n\u003cbr\u003e\n\n## 4. How do you declare _variables_ in _TypeScript_?\n\nIn TypeScript, **variable** **declarations** support different methodologies for declaring variables and their associated types.\n\n### Variable and Type Declaration Methods\n\n#### 1. var\n\n```typescript\nvar score: number = 100;\n```\n\nThis declaration can lead to **variable hoisting** and has global scope or function-level scope.\n\n#### 2. let\n\nUse `let` when you want to define variables within a **block scope**. This is the recommended default choice:\n\n```typescript\nlet playerName: string = \"John\";\n```\n\n#### 3. const\n\n`const` allows you to declare **constants** and is especially useful for maintaining data integrity:\n\n```typescript\nconst apiKey: string = \"your-api-key-here\";\n```\n\n#### 4. Function Scope\n\nAll three methods (`var`, `let`, and `const`) are confined to their immediate function scope:\n\n```typescript\nfunction doSomething() {\n  let tempValue: number = 42;\n  var result: boolean = true;\n}\n```\n\n### Rules for Variable Declaration and Initialization\n\n- **Order Matters**: In TypeScript, a variable must be declared before being used. This is not a requirement in JavaScript, but good JavaScript practice is to declare a variable before using it.\n\n  If you're dealing with complex or interconnected codes, it's a good practice to use the `let` and `const` declarations that ensure the block-level scoping, thus helping with potential hoisting issues.\n\n- **Static Types**: TypeScript requires that you declare the data type of a variable (or let the system infer it) and then initialize it with a value of exactly the same type:\n\n  ```typescript\n  let count: number;  // Declaration\n  count = 42;  // Allowed\n  count = \"42\";  // Error! Type 'string' is not assignable to type 'number'.\n  ```\n\n- **Type Inference**: TypeScript can often infer the variable's type based on its initialization value. This reduces the need to specify a type explicitly.\n\n  ```typescript\n  let word = \"hello!\";  // TypeScript infers the type as 'string' because of the initialization.\n  ```\n\n### Best Practices for Variable Declarations\n\n- **Use `const` Where You Can**: This approach isn't always possible, especially when dealing with object properties. However, favor `const` for better code readability and to prevent accidental data mutations.\n\n- **Prefer `let` over `var`**: `let` adheres better to **block-level scoping** and offers more predictability in the code.\n\n- **Initialize at Declaration**: Although TypeScript allows initializations after declarations, it's best to declare and initialize variables simultaneously to improve code clarity and type safety.\n\n- **Prefer Type Annotations**: Explicitly specifying variable types can improve code readability. However, when the variable type is obvious from the initialization, type inference should suffice.\n\u003cbr\u003e\n\n## 5. What are _Interfaces_ in _TypeScript_ and how do they work?\n\nIn TypeScript, an **interface** defines the structure and types of its members. It acts as a contract for the required properties and methods, ensuring that implementing classes or objects match this structure.\n\n### Key Features of Interfaces\n\n- **Type Consistency**: Objects that adhere to an interface's structure are considered compatible with it.\n- **Optional and Readonly Members**: Interfaces allow for optional attributes and readonly members with the `?` and `readonly` keywords respectively.\n- **Call Signatures**: Interfaces can define method types, specifying function parameter and return types.\n- **Index Signatures**: Useful for specifying that an object can have any number of properties, all of a certain type.\n\n### Core Use-Cases\n\n- **Standardizing Objects**: Ensuring that disparate objects share a common structure for increased cohesiveness and ease of use.\n- **Contract Enforcement**: Enforcing property and method requirements on classes to reduce errors and improve maintainability.\n\n### Code Example: Basic Interface\n\nHere is the TypeScript code:\n\n```typescript\ninterface Point {\n    x: number;\n    y: number;\n}\n  \nfunction printPoint(p: Point) {\n    console.log(`Point coordinates: (${p.x}, ${p.y})`);\n}\n\nlet pointA = { x: 3, y: 7 }; // This object matches Point's structure\nlet pointB = { x: 8 }; // This object is missing the 'y' property\n\nprintPoint(pointA); // Output: Point coordinates: (3, 7)\nprintPoint(pointB); // Compile-time error due to incorrect structure\n```\n\u003cbr\u003e\n\n## 6. Describe the _Enum_ type and when you might use it.\n\nThe **Enum** is a data type that simplifies the representation and management of discrete, named values. It's a foundational tool to ensure **type safety** in TypeScript and a number of vital use-cases:\n\n- **Reducing 'Magic Values'**: When ensuring readability and preventing repetitive literal values, such as `1`, `2`, or `'red'`.\n- **Configuring Behaviour**: influencing functionalities sets of associated values, such as HTTP methods, ordering or customer types.\n- **Ensuring Type Safety and Efficiency**: The predefined set of valid members and a clear data type ensures that value assignments and operations are unequivocal and consistent.\n\n### Core Components\n\n- **Key**: a unique identifier, typically a number or string.\n- **Value**: Data associated with the key. If not provided, the key is used as the value.\n\n### Standard, String, and Heterogeneous Enums\n\n- **Standard Enum**: Every key and value are of the same data type, typically numbers.\n- **String Enum**: All keys and values must be strings, ensuring consistent data representation.\n- **Heterogeneous Enum**: Defines keys with both number or string values. However, due to the mixed-type nature of these enums, it's best to steer clear of them in most cases.\n\n### Code Example: Standard Enum\n\nHere is the TypeScript code:\n\n```typescript\nenum HttpMethods {\n  GET,\n  POST,\n  PUT,\n  DELETE\n}\n\nconst requestType: HttpMethods = HttpMethods.GET;\n\n// ❌ This is not allowed due to type safety\n// const requestType2: HttpMethods = 'GET';\n```\n\nIn the example, the key `GET` is implicitly assigned the value `0`.\n\n### Code Example: String Enum\n\nHere is the TypeScript code:\n\n```typescript\nenum MediaTypes {\n  Image = 'image',\n  Video = 'video',\n  Audio = 'audio'\n}\n\nconst selectedType: MediaTypes = MediaTypes.Image;\n\n// ✅ Accessing the value\nconst associatedText: string = MediaTypes.Image;\n\n// ❌ This is not allowed due to type safety\n// const invalidType: MediaTypes = 'image';\n```\n\n the Enum helps ensure the proper data type and its values.\n\n### Pragmatic Use of Enums\n\nWhile Enums are a powerful tool for maintaining type safety, simplify associating related sets of values.\n\nHowever, a consideration is that an Enum value can be inferred or forced to be of any key and underlying value type.\n\n### Potential Downsides of Enums\n\n- **Compilation Impact**: When used in a broader context, or in data structures like arrays or maps, TypeScript generates additional code to convert Enum keys to their associated values.\n- **Memory Usage**: Every usage of an Enum requires memory allocation for its value.\n\nWhen a simple constant would suffice or if there's a need for a more dynamic relationship between keys and values, detailed types would be a better alternative.\n\u003cbr\u003e\n\n## 7. How do you define and use a _function_ in _TypeScript_?\n\nWhen defining a **function** in TypeScript, you have the following fundamental components to consider:\n\n- **Function Signature**: Comprising the function's purpose, parameters, type, and return value.\n- **Function Body**: Containing the actual operation or series of steps the function will execute.\n\n### Key Concepts\n\n#### 1) Function Declaration\n\nTo declare a function, you specify its name, its parameter list, and its return type. If the function doesn't return a value, you set the return type to `void`.\n\nHere is a code example:\n\n```typescript\nfunction greet(name: string): void {\n    console.log(`Hello, ${name}!`);\n}\n```\n\n#### 2) Function Expression\n\nYou can also declare functions using expressions, which involve assigning functions to variables as values. This approach allows you to be more flexible, such as when you're using **callbacks**.\n\nHere is an example:\n\n```typescript\nlet greet: (name: string) =\u003e void;\ngreet = function(name: string): void {\n    console.log(`Hello, ${name}!`);\n};\n```\n\n#### 3) Optional and Default Parameters\n\nTypeScript supports both **optional** and **default** function parameters, enhancing the flexibility of your functions.\n\n**Optional Parameters** are denoted by a `?` symbol after the parameter name.\n\nHere is the code example:\n\n```typescript\nfunction greet(name: string, title?: string) {\n    if (title) {\n        console.log(`Hello, ${title} ${name}!`);\n    } else {\n        console.log(`Hello, ${name}!`);\n    }\n}\n```\n\n**Default Parameters** are when you assign a default value to a parameter:\n\nHere is the code example:\n\n```typescript\nfunction greet(name = \"Stranger\") {\n    console.log(`Hello, ${name}!`);\n}\n```\n\n#### 4) Use Rest Parameters\n\nYou can define a parameter as a \"rest\" parameter, which means the function can accept any number of arguments for that parameter.\n\nHere is the code example:\n\n```typescript\nfunction introduce(greeting: string, ...names: string[]) {\n    console.log(`${greeting}, ${names.join(\", \")}!`);\n}\n\nintroduce(\"Hello\", \"Alice\", \"Bob\", \"Carol\");\n```\n\n#### 5) Function Overloads\n\nYou can declare multiple function **overloads** to define a set of parameters and their return types for a single function. This feature is especially beneficial when the function's behavior logically varies based on different input types.\n\nHere is the code example:\n\n```typescript\nfunction specialGreet(name: string): void;\nfunction specialGreet(title: string, name: string): void;\n\nfunction specialGreet(a: any, b?: any): void {\n    if (b) {\n        console.log(`Hello, ${a}, ${b}`);\n    } else {\n        console.log(`Hello, ${a}`);\n    }\n}\n```\n\n#### 6) Call Signature\n\nWhen using objects in TypeScript, you have the **call signature** to define the expected function structure for a specific method within the object.\n\nHere is a code example:\n\n```typescript\ntype Greeter = {\n    (name: string): void\n};\n\nlet welcome: Greeter;\nwelcome = function(name: string): void {\n    console.log(`Welcome, ${name}!`);\n};\n```\n\u003cbr\u003e\n\n## 8. What does \"_type inference_\" mean in the context of _TypeScript_?\n\nIn TypeScript, **type inference** is a core feature that allows the type of a variable to be automatically determined from its value. This provides the benefits of static typing without the need for explicit type annotations.\n\n### How It Works\n\nTypeScript employs a **best common type** algorithm to infer a variable's type. When TypeScript encounters multiple types for a variable during assignment or an array literal, it computes the **union** of these types and selects the best common type for the variable.\n\n### Code Example: Type Inference\n\nConsider the following code:\n\n```typescript\nlet value = 10; // Type 'number' inferred\nlet message = \"Hello, TypeScript!\"; // Type 'string' inferred\n\nfunction add(a: number, b: number) {\n    return a + b;\n}\n\nlet sum = add(5, 7); // Type 'number' inferred\n```\n\nTypeScript can infer the most likely type from the context, such as:\n\n- When a value is assigned immediately, TypeScript assigns the value's type to the variable.\n- Type information from adjacent types is used to determine the best common type. If all values are of a compatible type, that type is used.\n\n### Benefits of Type Inference\n\n- **Conciseness**: Eliminates the need for explicit type declarations, leading to more compact and readable code.\n- **Adaptability**: Codebase types align naturally with values, enhancing maintainability when values change.\n- **Error Reduction**: Reduces the risk of inconsistencies between the declared type and the actual value.\n\u003cbr\u003e\n\n## 9. Explain the use of '_let_' and '_const_' in _TypeScript_.\n\n**TypeScript** makes use of `const` and `let` for variable declaration. These two keywords offer explicitness, scoping, and immutability for efficient code maintenance.\n\n### Core Distinctions\n\n- **const**: Designates constants that remain unchanged once declared. It's important to note that this makes the reference immutable but doesn't actively prevent alteration of the internal state for complex objects like arrays. \n\n- **let**: Initiates variables with standard mutable behavior.\n\n### Code Example: `const`\n\nHere is the TypeScript code:\n\n```typescript\nconst productId: number = 5;\nlet productName: string = 'Tesla';\n\nconst getProductDetails = (id: number): string =\u003e {\n  return `Product ID: ${id}`;\n};\n\n// Attempting to modify will result in a compilation error\n// productId = 6;\n\n// Reference is still immutable\nconst anotherProductId: number = 10;\n// This will throw a compilation error since it's a constant\n// anotherProductId = 12;\n\n// Modifying internal state of an object is allowed for a const\nconst myArray: number[] = [1, 2, 3];\nmyArray.push(4);\n```\n\n### Code Example: `let`\n\nHere is the TypeScript code:\n\n```typescript\nlet vehicleType: string = 'Car';\n\nif (true) {\n  let vehicleType: string = 'Motorcycle';\n  console.log(vehicleType);  // Output: Motorcycle\n}\n\nconsole.log(vehicleType);  // Output: Car\n```\n\u003cbr\u003e\n\n## 10. How do you compile _TypeScript_ files into _JavaScript_?\n\nCompiling **TypeScript** (.ts) into **JavaScript** (.js) involves integrating a TypeScript compiler (`tsc`). You can customize the compilation process using `tsconfig.json` and even adopt more advanced methods to suit project needs:\n\n### Workflow Steps\n\n1. **File Creation**: Write TypeScript files (.ts).\n \n2. **Compiler Config**: Set up a `tsconfig.json` file with compilation options.\n\n3. **Compile**: Execute the `tsc` command to initiate the compilation process.\n\n4. **Output Verification**: Review the generated JavaScript files.\n\n\n#### TypeScript Configuration (`tsconfig.json`)\n\nHere is the `tsconfig.json` file. The full configuration guide is available [here](https://www.typescriptlang.org/tsconfig).\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"ES5\",\n    \"module\": \"commonjs\",\n    \"strict\": true,    \n    \"outDir\": \"dist\",\n    \"rootDir\": \"src\"  \n  },\n  \"include\": [\n    \"src/**/*.ts\"    \n  ],\n  \"exclude\": [      \n    \"node_modules\",   \n    \"**/*.spec.ts\"    \n  ]\n}\n```\n\n### Practical Example: Vineyard Residential Task Management App\n\nHere is a practical and comprehensive `tsconfig.json` file.\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"module\": \"commonjs\",\n    \"lib\": [\"dom\", \"es2015\", \"es5\", \"es6\", \"es7\", \"es2015.collection\"],\n    \"allowJs\": true,\n    \"checkJs\": false,\n    \"jsx\": \"react\",\n    \"declaration\": false,\n    \"sourceMap\": true,\n    \"outDir\": \"dist\",  \n    \"rootDir\": \"src\",\n    \"strict\": true,\n    \"noImplicitAny\": true,\n    \"noImplicitThis\": true,\n    \"moduleResolution\": \"node\",\n    \"esModuleInterop\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"removeComments\": true,\n    \"suppressImplicitAnyIndexErrors\": true,\n    \"typeRoots\": [\"node_modules/@types\", \"custom-typings\"],\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"components/*\": [\"src/components/*\"],\n      \"utils/*\": [\"src/utils/*\"],\n    },\n    \"experimentalDecorators\": true,\n    \"emitDecoratorMetadata\": true,\n    \"incremental\": true,\n    \"diagnostics\": true,\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"newLine\": \"LF\",\n    \"watchOptions\": {\n      \"watchFile\": \"useFsEvents\",  \n      \"fallbackPolling\": \"dynamicPriority\",   \n      \"polling\": true,\n      \"esModuleInterop\": true,\n            \"pollingInterval\": 2500,\n      \n      \"followSymlinks\": true\n    }\n  },\n  \"include\": [\n    \"src/**/*.ts\",\n    \"src/**/*.tsx\",\n    \"@types\"\n  ],\n  \"exclude\": [\n    \"node_modules\",\n    \"dist\"\n  ]\n}\n```\n\n### Advanced Configuration\n\n- **Project Reference**: Useful for code splitting in large projects.\n- **Custom Transformers**: Employ custom logic during the compilation process.\n- **Programmatic API**: Provides flexibility in managing compiler settings and execution.\n\u003cbr\u003e\n\n## 11. Explain _classes_ in _TypeScript_. How are they different from _ES6 classes_?\n\nWhile TypeScript and **ES6** classes share many similarities, TypeScript's classes offer additional features and strong typing to make your code more robust.\n\n### Key Shared Class Features\n\n- **Inheritance**: Subclasses (children) can extend parent classes, inheriting their methods and properties.\n- **Polymorphism**: Derived classes can define methods with the same name as their parent.\n- **Encapsulation**: Data hiding is supported through access modifiers, such as `public`, `private`, and `protected`.\n- **Constructor**: Instantiation starts with a constructor method, if defined.\n\n### Unique TypeScript Class Features\n\n#### Field Declaration\n\nIn TypeScript, you can specify fields directly in the class without initializing them. Automatic initialization to `undefined` occurs during object creation. ES6 requires initializing fields in the constructor or within their declaration.\n\n```typescript\nclass Example {\n    // Field is automatically initialized to undefined upon object creation\n    someField: string;\n}\n```\n\n#### Abstract Classes\n\nTypeScript supports abstract classes to serve as a blueprint for other classes. They cannot be instantiated on their own but can provide some implementation that derived classes can override.\n\n```typescript\nabstract class AbstractExample {\n    abstract someMethod(): void;  // Method has no implementation (abstract)\n}\n```\n\n#### Readonly Properties\n\nYou can mark class properties as `readonly`, ensuring they are only set upon declaration or within the class constructor.\n\n```typescript\nclass Example {\n    readonly id: number;\n    constructor(id: number) {\n        this.id = id;  // Readonly can only be assigned in the constructor or declaration\n    }\n}\n```\n\n#### Static Members\n\nClasses in TypeScript support static members, such as properties and methods that belong to the class itself, rather than to instances of the class.\n\n```typescript\nclass Example {\n    static count = 0;  // Static property\n    static incrementCount() {\n        Example.count++;\n    }\n}\n```\n\n#### Accessor Functions\n\nYou can define `get` and `set` functions in TypeScript, known as accessor functions, to control how class properties are accessed and modified.\n\n```typescript\nclass Example {\n    private _name: string;\n\n    get name(): string {\n        return this._name;\n    }\n\n    set name(newName: string) {\n        this._name = newName.trim();\n    }\n}\n```\n\n#### Parameter Properties\n\nTypeScript provides a shortcut to declare a property and initialize it from the constructor parameter. This method can make code more concise, especially when a constructor parameter corresponds directly to a class property.\n\n```typescript\nclass Example {\n    constructor(private _name: string, public age: number) {\n        // Private _name property created and initialized from constructor parameter\n        // Public age property created and initialized from constructor parameter\n    }\n}\n```\n\n#### Intersection Types for Classes\n\nIn TypeScript, when you define a base class and then later extend it, you are creating an intersection type. This means the child class will inherit all the properties and methods from both its parent(s) and itself.\n\n### ES6 Additional Features not Present in TypeScript\n\n#### Class Expressions\n\nBoth ES6 and TypeScript support class expressions, which allows you to define a class without a class name.\n\nIn ES6:\n\n```javascript\nconst Animal = class {\n    // Class methods and properties defined here\n};\n```\n\n#### Iterator Protocol\n\nES6 classes support the Iterator protocol, making it easier to iterate over objects.\n\n```typescript\nclass IterableExample implements Iterable\u003cstring\u003e {\n    // Implement iterator function for strings\n    [Symbol.iterator]() {\n        let index = 0;\n        const data = ['one', 'two', 'three'];\n        return {\n            next: () =\u003e {\n                if (index \u003c data.length) {\n                    return { value: data[index++], done: false };\n                }\n                return { value: undefined, done: true };\n            }\n        };\n    }\n}\n```\n\u003cbr\u003e\n\n## 12. How do you implement _Inheritance_ in _TypeScript_?\n\nLet's look at how you can use **inheritance** in TypeScript using both **ES6 classes** and **prototypal inheritance**.\n\n### 1. Inheritance with ES6 Class Syntax\n\nWith the advent of ES6, a more familiar class-based inheritance method was introduced. This method is usually easier to read and understand.\n\n#### Code Example: Inheritance using ES6 Classes\n\nHere is the TypeScript code:\n\n```typescript\nclass Animal {\n  private name: string;\n\n  constructor(theName: string) {\n    this.name = theName;\n  }\n\n  move(distanceInMeters: number = 0) {\n    console.log(`${this.name} moved ${distanceInMeters}m.`);\n  }\n}\n\nclass Snake extends Animal {\n  constructor(name: string) {\n    super(name);\n  }\n\n  move(distanceInMeters = 5) {\n    console.log(\"Slithering...\");\n    super.move(distanceInMeters);\n  }\n}\n\nconst mySnake = new Snake(\"Cobra\");\nmySnake.move();  // Output: Slithering... Cobra moved 5m.\n```\n\n### 2. Inheritance with Prototypal Methodology\n\nPrior to ES6, TypeScript, like JavaScript, used a **prototypal** inheritance approach.\n\nThe prototypal mechanism can be useful when developing complex object structures, but it is important to be aware of the nuances in order to avoid unexpected behavior.\n\n#### Code Example: Prototypal Inheritance in TypeScript\n\nHere is the TypeScript code:\n\n```typescript\n// Define the Parent Class\nfunction Animal(this: Animal, name: string) {\n  this.name = name;\n}\n\nAnimal.prototype.move = function(distanceInMeters: number = 0) {\n  console.log(`${this.name} moved ${distanceInMeters}m.`);\n};\n\n// Define the Child Class\nfunction Snake(name: string) {\n  Animal.call(this, name);\n}\n\n// Set up the Inheritance\nSnake.prototype = Object.create(Animal.prototype);\nSnake.prototype.constructor = Snake;\n\n// Override the Base Type's Method\nSnake.prototype.move = function(distanceInMeters = 5) {\n  console.log(\"Slithering...\");\n  Animal.prototype.move.call(this, distanceInMeters);\n};\n\nconst mySnake = new Snake(\"Cobra\");\nmySnake.move();  // Output: Slithering... Cobra moved 5m.\n```\n\n#### Simplified Methods\n\nUsing the prototypal construct can be perplexing at first, but its strength lies in its flexibility.\n\n  You can avoid the complexities of direct prototype assignments using ES5 derived constructions, as seen next:\n\n```typescript\nfunction Animal(name: string) {\n  this.name = name;\n}\n\nAnimal.prototype.move = function(distanceInMeters: number = 0) {\n  console.log(`${this.name} moved ${distanceInMeters}m.`);\n};\n\nfunction Snake(name: string) {\n  Animal.call(this, name);\n}\n\n// Utilize `Object.create` for simplified prototype delegation\nSnake.prototype = Object.create(Animal.prototype);\nSnake.prototype.constructor = Snake;\n\nSnake.prototype.move = function(distanceInMeters = 5) {\n  console.log(\"Slithering...\");\n  Animal.prototype.move.call(this, distanceInMeters);\n};\n```\n\u003cbr\u003e\n\n## 13. What are _access modifiers_ and how do they work in _TypeScript_?\n\n**Access modifiers** are TypeScript's way of controlling class member visibility and mutability. They enforce encapsulation and are especially useful for object-oriented design.\n\n### Key Modifiers\n\n- **Public**: Default for class members. They are accessible from both inside and outside the class.\n\n- **Protected**: Members can be accessed within the class and its subclasses. They help establish the \"is-a\" relationship.\n\n- **Private**: Marks members as accessible only within the declaring class. This ensures they're not modified or accessed externally.\n\n#### Code Example: Access Modifiers in Action\n\nHere is the TypeScript code:\n\n```typescript\nclass Person {\n    public name: string;\n    private age: number;\n    protected contact: string;\n\n    constructor(name: string, age: number, contact: string) {\n        this.name = name;\n        this.age = age;\n        this.contact = contact;\n    }\n}\n\nclass Employee extends Person {\n    private employeeId: string;\n\n    constructor(name: string, age: number, contact: string, employeeId: string) {\n        super(name, age, contact);\n        this.employeeId = employeeId;\n    }\n\n    public displayDetails(): void {\n        console.log(`${this.name} - ${this.age} - ${this.contact} - ${this.employeeId}`);\n    }\n}\n\n// Somewhere in your code\nconst person = new Person(\"John Doe\", 30, \"1234567\");\nconsole.log(person.name);  // Accessible\nconsole.log(person.age);   // ERROR: 'age' is private\n\nconst employee = new Employee(\"Jane Doe\", 25, \"2345678\", \"E123\");\nconsole.log(employee.contact);  // ERROR: 'contact' is protected\nemployee.displayDetails();     // Correctly displays details\n\nemployee.age = 35;    // ERROR: 'age' is private\nemployee.contact = \"3456789\";  // ERROR: 'contact' is protected\n```\n\u003cbr\u003e\n\n## 14. Discuss _Abstract classes_ and their purposes in _TypeScript_.\n\nIn TypeScript, **abstract classes serve as blueprints** that guide derived classes, essentially laying out the structure without necessarily providing complete implementations of methods. \n\n### Core Features of Abstract Classes\n\n#### Method Signatures\n\n**Abstract classes define method signatures** without specifying their functionality. This feature provides a comprehensive form for derived classes to work from.\n\n#### Specific Method Definitions\n\nIn addition to method signatures, abstract classes can contain completely implemented methods. These methods either support the abstract methods or serve as independent functionalities.\n\n#### Abstract and Non-Abstract Members Separation\n\nAbstract classes clearly demarcate between methods that require implementation by derived classes and those that are either fully implemented or optional.\n\n### Common Use-Cases for Abstract Classes\n\n- Facilitate Reusability: Abstract classes help in consolidating common or shared functionalities among several derived classes.\n\n- Contract Enforcement: They ensure that derived classes conform to a shared structure, guaranteeing a defined set of methods that must be implemented.\n\n- Partial Implementations: Abstract classes allow for a mix of fully implemented methods alongside those requiring concrete implementations in derived classes.\n\n### TypeScript Utility: Static Properties\n\nAbstract classes in TypeScript can have **static members**, which belong to the class itself and not to any specific instance. This feature provides a convenient way to define properties or methods that are accessible without the need for class instantiation.\n\n### Code Example: Abstract Class\n\nHere is the TypeScript code:\n\n```typescript\nabstract class Shape {\n    abstract getArea(): number;\n    abstract getPerimeter(): number;\n    color: string;\n\n    constructor(color: string) {\n        this.color = color;\n    }\n\n    static defaultColor: string = 'red';\n\n    describe() {\n        return `This shape is ${this.color}.`;\n    }\n}\n\n// This will throw an error because the derived class does not provide concrete implementations for abstract methods.\nclass Circle extends Shape { \n    constructor(public radius: number, color: string) {\n        super(color);\n    }\n\n    // The 'Circle' class inherited the following properties from 'Shape', but neither implements nor specifies them in the derived class: 'getArea' and 'getPerimeter'.\n    getArea(): number {\n        return Math.PI * this.radius ** 2;\n    }\n\n    getPerimeter(): number {\n        return 2 * Math.PI * this.radius;\n    }\n}\n\nconst myCircle = new Circle(5, 'blue');\nconsole.log(myCircle.getArea()); // Outputs: 78.54\nconsole.log(myCircle.describe()); // Outputs: This shape is blue.\nconsole.log(Shape.defaultColor); // Outputs: red\n```\n\u003cbr\u003e\n\n## 15. Can you describe the use of _Constructors_ within _TypeScript classes_?\n\n**TypeScript** provides a convenient way to define **constructors** for classes using the `constructor` keyword. A constructor method allows you to initialize class members and can have access specifiers. They are useful for setting up an object's initial state.\n\n### Key Features\n\n- **Automatic Invocation**: The constructor is automatically called when an object of the class is instantiated.\n- **Single Unique Constructor**: A class can only have one constructor, providing a centralized place for initialization.\n- **Overload Capabilities**: You can overload a constructor to define multiple ways of object initialization.\n\n### Example: Constructor in TypeScript\n\nWe use the `this` keyword to refer to the current instance, ensuring proper data assignment.\n\n```typescript\nclass Person {\n  // Member variables\n  name: string;\n  age: number;\n  \n  // Constructor\n  constructor(name: string, age: number) {\n    this.name = name;\n    this.age = age;\n  }\n}\n```\n\n### Constructor Access Modifiers\n\nTypeScript supports **access modifiers** on constructor parameters, enabling concise and safe class initialization.\n\n- **Public**: Parameters without a modifier are public by default.\n- **Private**: Adding the `private` keyword makes them accessible within the class only.\n- **Read-Only**: Combining `readonly` with parameter and the private or public access modifier ensures the parameter is assigned a value just once, in the constructor.\n\u003cbr\u003e\n\n\n\n#### Explore all 100 answers here 👉 [Devinterview.io - Typescript](https://devinterview.io/questions/web-and-mobile-development/typescript-interview-questions)\n\n\u003cbr\u003e\n\n\u003ca href=\"https://devinterview.io/questions/web-and-mobile-development/\"\u003e\n\u003cimg src=\"https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/github-blog-img%2Fweb-and-mobile-development-github-img.jpg?alt=media\u0026token=1b5eeecc-c9fb-49f5-9e03-50cf2e309555\" alt=\"web-and-mobile-development\" width=\"100%\"\u003e\n\u003c/a\u003e\n\u003c/p\u003e\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevinterview-io%2Ftypescript-interview-questions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdevinterview-io%2Ftypescript-interview-questions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevinterview-io%2Ftypescript-interview-questions/lists"}