{"id":23148365,"url":"https://github.com/piyalidas10/typescript-interview-questions-answers","last_synced_at":"2025-04-04T13:45:16.932Z","repository":{"id":268392014,"uuid":"904180386","full_name":"piyalidas10/TypeScript-Interview-Questions-Answers","owner":"piyalidas10","description":"TypeScript-Interview-Questions-Answers","archived":false,"fork":false,"pushed_at":"2025-02-20T05:59:17.000Z","size":180,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-20T06:30:53.491Z","etag":null,"topics":["interview","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","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/piyalidas10.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}},"created_at":"2024-12-16T11:58:51.000Z","updated_at":"2025-02-20T05:59:20.000Z","dependencies_parsed_at":null,"dependency_job_id":"70b23e26-7667-4381-be09-c931b25c8861","html_url":"https://github.com/piyalidas10/TypeScript-Interview-Questions-Answers","commit_stats":null,"previous_names":["piyalidas10/typescript-interview-questions-answers"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/piyalidas10%2FTypeScript-Interview-Questions-Answers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/piyalidas10%2FTypeScript-Interview-Questions-Answers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/piyalidas10%2FTypeScript-Interview-Questions-Answers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/piyalidas10%2FTypeScript-Interview-Questions-Answers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/piyalidas10","download_url":"https://codeload.github.com/piyalidas10/TypeScript-Interview-Questions-Answers/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247189721,"owners_count":20898692,"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","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":["interview","typescript"],"created_at":"2024-12-17T17:11:00.082Z","updated_at":"2025-04-04T13:45:16.919Z","avatar_url":"https://github.com/piyalidas10.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# TypeScript-Interview-Questions-Answers\n\n#### Advantages of Typescript over Javascript\nhttps://www.totaltypescript.com/tsconfig-cheat-sheet\n\n\n\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 1   |  Does Typescript run in the browser ? \u003cbr\u003e\u003cbr\u003e TypeScript cannot be run or understood in any browser. So, TypeScript is compiled to JavaScript (which browsers can understand) using TSC(TypeScript) compiler. To install TSC compoiler, we have to install Node.js as we need NPM.\n| 2   |  What is TypeScript? \u003cbr\u003e\u003cbr\u003e TypeScript is a statically typed language and a superset of JavaScript that builds on top of JavaScript’s existing syntax and functionality. This means that you can use JavaScript in your TypeScript code, but you can't use TypeScript in your JavaScript code as code written in TypeScript uses features and syntax not present in JavaScript. TypeScript must be compiled (transpiled is another term as it isn’t converting to a low-level language) to JavaScript to run in web browsers and in environments like Node.js. The file extension for TypeScript is .ts. \n| 3   |  Undefined vs Null ? \u003cbr\u003e\u003cbr\u003e Undefined means the variable is written there but there is no existence of it in the memory. Undefined is a data type. `let a: number; console.log(a); console.log(typeof a);` \u003cbr\u003e Null is a value whose type is Object. `let a = null; console.log(a); console.log(typeof a);` \n| 4   |  What is template literals or Template strings? \u003cbr\u003e\u003cbr\u003e Template literals, also known as template strings, are a feature in JavaScript that allow for easier string interpolation and multi-line strings. They are denoted by backticks instead of single or double quotes. \u003cbr/\u003e\u003cbr/\u003e 1) Display variable value without using concatenation `let a = 90; let str = 'value of a is ${a}'; console.log(str);` \u003cbr/\u003e 2) The way you write string inside, it will appear as it is. `let str = 'one          two         three'; console.log(str);`\n| 5   |  What is a type alias in TypeScript? \u003cbr\u003e\u003cbr\u003e Type aliases in TypeScript allow you to create custom names for complex types, making your code more readable and maintainable. They are particularly useful when dealing with complex data structures, union types, and other scenarios where you want to give a clear name to a specific type. https://www.freecodecamp.org/news/how-typescript-type-aliases-work/\n| 6   |  What is an union type in TypeScript? \u003cbr\u003e\u003cbr\u003e A union type describes a value that can be one of several types. We use the vertical bar ( | ) to separate each type, so number | string | boolean is the type of a value that can be a number , a string , or a boolean . `type pincode = number | string; function printStatusCode(code: string | number) {};`\n| 7   |  What is never type TypeScript? \u003cbr\u003e\u003cbr\u003e never type represents the type of values that never occur. \u003cstrong\u003eNever\u003c/strong\u003e means This function will not complete till the last line and before the finish it breaks so it will never return a value. Here you may have a question that when the function is not returning anything, then why don't we use Void as a return type? Well, because there is a difference. \u003cstrong\u003eGenerally a function not returning anything can be defined as void, but still returns undefined. But if you have never data type, it will give a compile time error. \u003c/strong\u003e let see the code `let x: void = undefined; let y: never = undefined;` you will get error on never type \"Type 'undefined' is not assignable to type 'never'.\" \u003cbr/\u003e https://www.typescriptlang.org/docs/handbook/basic-types.html#:~:text=The%20never%20type%20represents%20the,that%20can%20never%20be%20true.\n| 8   |  Never vs Void ? \u003cbr\u003e\u003cbr\u003e The difference between never and void that you can assign null or undefined to void type, but you cannot do the same with never type. `let x: void = undefined; let y: never = undefined;` you will get error on never type \u003cstrong\u003e\"Type 'undefined' is not assignable to type 'never'.\"\u003c/strong\u003e\n| 9   |  Use of module in tsconfig.json ? \u003cbr\u003e\u003cbr\u003e Using module option, TypeScript docs describe the module compiler option by which TSC compile typescript file to JavaScript. Specify module code generation: \"None\", \"CommonJS\", \"AMD\", \"System\", \"UMD\", \"ES6\", \"ES2015\" or \"ESNext\". \u003cbr/\u003e\u003cbr/\u003e  1) \"module\": \"commonjs\" is basically used when you want to generate the nodejs related coding. When your typescript code is going to be used with node JS, then Commonjs is the module loader. 2) \"module\": \"ES2020\" is modern javascript, export statement will work directly. \u003cbr/\u003e https://www.tsmean.com/articles/learn-typescript/typescript-module-compiler-option/\n| 10   |  Use of lib in tsconfig.json ? \u003cbr\u003e\u003cbr\u003e lib option tells TypeScript what built-in types to include. lib option is being included in an array. \u003cstrong\u003ees2022\u003c/strong\u003e is the best option for stability. \u003cstrong\u003edom and dom.iterable\u003c/strong\u003e give you types for window, document etc. \u003cbr/\u003e https://www.typescriptlang.org/tsconfig/#lib\n| 10   |  Use of noEmit in tsconfig.json ? \u003cbr\u003e\u003cbr\u003e Tells TypeScript not to emit any files. This is important when you're using a bundler so you don't emit useless .js files.\n| 11   |  What is strict type checking? \u003cbr\u003e\u003cbr\u003e Strict type checking means the function prototype(function signature) must be known for each function that is called and the called function must match the function prototype. It is done at compile time. \u003cbr/\u003e `{ \"compilerOptions\": { \"strict\": true, \"noUncheckedIndexedAccess\": true, \"noImplicitOverride\": true } }` . \u003cbr/\u003e \u003cstrong\u003estrict:\u003c/strong\u003e Enables all strict type checking options. Indispensable. \u003cstrong\u003enoUncheckedIndexedAccess:\u003c/strong\u003e Prevents you from accessing an array or object without first checking if it's defined. This is a great way to prevent runtime errors, and should really be included in strict. \u003cstrong\u003enoImplicitOverride:\u003c/strong\u003e Makes the override keyword actually useful in classes.\n| 12   |  What is transpiling in typescript? \u003cbr\u003e\u003cbr\u003e Transpilation is about changing code written in one high-level language (like Typescript) into another (like JavaScript) that can run in places like web browsers or on servers using Nodejs. If you're transpiling your code (creating JavaScript files) with tsc, you'll want these options. \u003cbr/\u003e `{ \"compilerOptions\": { \"module\": \"NodeNext\", \"outDir\": \"dist\" }}` \u003cbr/\u003e \u003cstrong\u003emodule:\u003c/strong\u003e Tells TypeScript what module syntax to use. NodeNext is the best option for Node. moduleResolution: NodeNext is implied from this option. \u003cstrong\u003eoutDir:\u003c/strong\u003e Tells TypeScript where to put the compiled JavaScript files. dist is my preferred convention, but it's up to you.\n| 13   |  Why need declaration option in tsconfig.json? \u003cbr\u003e\u003cbr\u003e If you're building for a library, you'll want declaration: true. declaration: Tells TypeScript to emit .d.ts files. This is needed so that libraries can get autocomplete on the .js files you're creating. \u003cbr/\u003e\u003cbr/\u003e If you're building for a library in a monorepo, you'll also want these options. \u003cbr/\u003e `{  \"compilerOptions\": { \"declaration\": true, \"composite\": true, \"sourceMap\": true, \"declarationMap\": true}` \u003cbr/\u003e \u003cstrong\u003ecomposite:\u003c/strong\u003e Tells TypeScript to emit .tsbuildinfo files. This tells TypeScript that your project is part of a monorepo, and also helps it to cache builds to run faster. \u003cstrong\u003esourceMap and declarationMap:\u003c/strong\u003e Tells TypeScript to emit source maps and declaration maps. These are needed so that when consumers of your libraries are debugging, they can jump to the original source code using go-to-definition.\n| 14   |  What is a tuple in TypeScript? \u003cbr\u003e\u003cbr\u003e TypeScript introduced a new data type called Tuple. Tuple can contain two values of different data types. It can limit the number of elements along with the data type. `let employee: [number, string] = [1, \"Steve\"]; let customers: [number, string][]; customers = [[1, \"Steve\"], [2, \"Bill\"], [3, \"Jeff\"]];`\n| 15   |  What is a Union in TypeScript? \u003cbr\u003e\u003cbr\u003e TypeScript allows us to use more than one data type for a variable or a function parameter. This is called union type. When you want that a variable should be able to handle two or more data types. Then you can use a pipe sign That is the union type. \u003cbr/\u003e https://www.tutorialsteacher.com/typescript/typescript-union\n| 16   |  What is Narrowing in TypeScript? \u003cbr\u003e\u003cbr\u003e Type narrowing is a process of refining or narrowing down the type using certain conditions with a particular code block. \u003cbr/\u003e https://www.typescriptlang.org/docs/handbook/2/narrowing.html \u003cbr/\u003e https://medium.com/@hrishikesh.pandey9955/what-is-narrowing-in-typescript-047b4c450de4\n```\nfunction triple(value: number | string) {\n  if (typeof value === \"string\") {\n    return value.repeat(3);\n  }\n  return value * 3;\n}\n\n// Instanceof Narrowing:\nfunction printFullDate(date: string | Date) {\n  if (date instanceof Date) {\n    console.log(date.toUTCString());\n  } else {\n    console.log(new Date(date).toUTCString());\n  }\n}\n\n// Instanceof Narrowing:\nclass User {\n  constructor(public username: string) {}\n}\nclass Company {\n  constructor(public name: string) {}\n}\nfunction printName(entity: User | Company) {\n  if (entity instanceof User) {\n    entity;\n  } else {\n    entity;\n  }\n}\n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 17   |  What is type guards in TypeScript? \u003cbr\u003e\u003cbr\u003e Type guards enable you to instruct the TypeScript compiler to infer a specific type for a variable in a particular context. There are several types of type guards : 1) typeof 2) instanceof 3) Custom Type Guards \u003cbr/\u003e https://www.typescriptlang.org/docs/handbook/advanced-types.html\n| 18   |  What is static in TypeScript? \u003cbr\u003e\u003cbr\u003e In TypeScript, you can use the static keyword to define static class members, including properties. A static property is a property that is shared across all instances of a class, and can be accessed without creating an instance of the class. \n```\nclass Counter {\n    static count: number = 0;\n\n    static increment() {\n        Counter.count++;\n    }\n}\nconsole.log(Counter.count);  // Output: 0\nCounter.increment();\nconsole.log(Counter.count);  // Output: 1\n\nAdvantages of Using 'static'\nShared State: Static properties allow you to maintain shared state across all instances of a class. This can be valuable for scenarios where maintaining a common value or counter is required.\nUtility Functions: Static methods are excellent for creating utility functions that are related to the class but don't require an instance to operate. They keep the class's namespace clean by not cluttering it with instance-specific methods.\nSingular Configuration: When you need configuration settings that apply to the entire class, using static properties can centralize this configuration without needing to replicate it across instances.\nFactory Methods: Static methods can be used as factory methods to create instances of a class with specific configurations, simplifying the process of instance creation.\n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 19  |  Advantages of Enum in TypeScript? \u003cbr\u003e\u003cbr\u003e \n```\nexport enum AppData {\n  APPSERVER = 1.0,\n  DT = Date.now()\n}\nconsole.log(AppData); // {1: \"APPSERVER\", APPSERVER: 1, DT: 1735204902342, 1735204902342: \"DT\"}\n\nlet a = 3;\nlet b = 6;\nexport enum Result {\n  SUM = sum(a, b)\n}\nfunction sum(a, b) {\n  return a + b;\n}\nconsole.log(Result); // {9: \"SUM\", SUM: 9}\n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 20 |  What will the output of `const {a=90, b} = {}; console.log(a, b);`? \u003cbr\u003e\u003cbr\u003e Ans. 90 undefined \n| 21  |  an interface and a class in TypeScript? \u003cbr\u003e\u003cbr\u003e A class is a blueprint from which we can create objects that share the same configuration - properties and methods. An interface is a group of related properties and methods that describe an object, but neither provides implementation nor initialisation for them. \n| 22  |  What are abstract classes? \u003cbr\u003e\u003cbr\u003e Ans. An abstract class is a class that you cannot create an instance, but it serves as a base class to the extended classes or subclasses. It includes both abstract and regular methods. It is a class that is inherited by multiple classes. We cannot create objects of an abstract class. \u003cbr/\u003e https://stackblitz.com/edit/class-abstract-interface-myspgfqt?file=src%2Fapp%2Fapp.component.ts\n| 23  |  Why interface is preferred over abstract class? \u003cbr\u003e\u003cbr\u003e Ans. In general, you should choose interfaces over abstract classes. The use of an interface separates your design from any implementation details. Even if you declare a purely abstract class without any method implementations, you must inherit from it to define classes that share the behavior defined by its methods.\n| 24  |  Can a class inherit from more than two abstract classes? \u003cbr\u003e\u003cbr\u003e Ans. Yes, A class can inherit from any number of abstract classes.\n| 25  |  What is Class Accessors (getter \u0026 setter) ? \u003cbr\u003e\u003cbr\u003e The getter method is executed when you read/get the value. The setter method is executed when you assign a value to that property. \u003cbr/\u003e https://www.typescripttutorial.net/typescript-tutorial/typescript-getters-setters/ \n| 26  |  What is Interfaces ? \u003cbr\u003e\u003cbr\u003e TypeScript interfaces define the structure of an object, specifying property types and method signatures. They act as contracts, ensuring that objects adhere to a particular shape, enhancing type safety and code readability, and enabling features like optional properties, read-only properties, and interface inheritance. `interface IPerson { name: string; age: number; address?: string; display() =\u003e void; }  class Customer implements IPerson{ name: 'test', age: 20; display(){console.log('hi');}` \u003cbr/\u003e https://www.geeksforgeeks.org/what-is-interfaces-and-explain-it-in-reference-of-typescript/?ref=lbp \u003cbr/\u003e\u003cbr/\u003e \u003cstrong\u003eInterfaces can't be instantiated and are not compiled, classes can be instantiated and are compiled.\u003c/strong\u003e\n| 27  |  What is readonly property in Typescript ? \u003cbr\u003e\u003cbr\u003e In TypeScript, readonly properties in an object type ensure that a property can only be set during the object's initialization. Once assigned, the value of a readonly property cannot be changed, providing a way to create immutable object properties. \n```\ninterface Employee {\n  readonly name: string;\n}\nconst employee: Employee = { name: 'Michael Scott' };\nemployee.name = 'Oscar Martinez'; // will get compile error\n\nNo, readonly properties cannot be modified after the object is created. Any attempt to change the value of a readonly property will result in a TypeScript error.\n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 28  |  Readonly vs Const in Typescript ? \u003cbr\u003e\u003cbr\u003e readonly applies to object properties and prevents modification after initialization, while const applies to variables and prevents reassignment of the variable itself, not its contents if it's an object or array. \u003cbr/\u003e A const variable cannot be re-assigned, just like a readonly property. Essentially, when you define a property, you can use readonly to prevent re-assignment. This is actually only a compile-time check. When you define a const variable (and target a more recent version of JavaScript to preserve const in the output), the check is also made at runtime.\n```\nlet tuple: Readonly\u003c[number, string]\u003e = [0, ''];\ntuple.shift(); // Property 'shift' does not exist on type 'readonly [number, string]'.\ntuple.pop(); // Property 'pop' does not exist on type 'readonly [number, string]'.\n\nconst Arr = [1,2,3];\n\nArr[0] = 10;   //OK\nArr.push(12); // OK\nArr.pop(); //Ok\n//But\nArr = [4,5,6] // ERROR\n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 29  |  When \u0026 why use Generics in Typescript ? \u003cbr\u003e\u003cbr\u003e Generics enables developers to write reusable and type-safe code. Generics allow you to create components that can work over a variety of types rather than a single one. When you start needing a generic is when you truly don't know what the type is going to be passed into the function, class, interface, constant.\n```\nfunction add\u003cT, U\u003e(a:T, b:U) {\n    console.log(a+b);\n}\nadd\u003cnumber, string\u003e(1, 'hi');\nadd\u003cstring, number\u003e('hi', 1);\n----------------------------------------------------------------------\nclass Box\u003cT\u003e {\n    private value: T;\n    constructor(value: T) {\n        this.value = value;\n    }\n    getValue(): T {\n        return this.value;\n    }\n}\nlet box = new Box\u003cnumber\u003e(42);\nconsole.log(box.getValue()); // Output: 42\n----------------------------------------------------------------------\ninterface Pair\u003cT, U\u003e {\n    first: T;\n    second: U;\n}\nlet pair: Pair\u003cnumber, string\u003e = { first: 1, second: \"two\" };\nconsole.log(pair); // Output: { first: 1, second: \"two\" }\n\nfunction reverse\u003cT\u003e(array: T[]): T[] {\n    return array.reverse();\n}\n----------------------------------------------------------------------\nlet numbers: number[] = [1, 2, 3, 4, 5];\nlet reversedNumbers: number[] = reverse(numbers);\nconsole.log(reversedNumbers); // Output: [5, 4, 3, 2, 1]\n```\n\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 29  |  What is Generic Constraints in Typescript ? \u003cbr\u003e\u003cbr\u003e In TypeScript, generic constraints restrict the types that can be used with a generic type by using the extends keyword.\n```\nfunction getLength\u003cT\u003e(v: T): void {\n    console.log(v.length); // will get error \"property length doesn't exist on type T\"\n}\ngetLength('Hi');\n\nNow here we want to put a constraint that allows to pass only those values which have length property. string in our case\n--------------------------------------------------------------------------------------------\ninterface IC {\n    length: number;\n}\nfunction getLength\u003cT extends IC\u003e(v: T): void {\n    console.log(v.length); // display 2\n}\ngetLength('Hi');\n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 29  |  What is Namespace in Typescript ? \u003cbr\u003e\u003cbr\u003e TypeScript, a namespace is a way to organize code into logical groups and avoid naming collisions between identifiers. Namespaces provide a way to group related code into a single namespace or module so that we can manage, reuse and maintain our code easily.\n\n\u003ch5\u003eBenefits of Using Namespaces:\u003c/h5\u003e\n\u003cstrong\u003eLogical grouping:\u003c/strong\u003estrong\u003e Namespaces provide a way to group related code into a single namespace or module, making it easier to manage and maintain your code.\n\u003cstrong\u003eAvoid naming collisions:\u003c/strong\u003e Namespaces help to avoid naming collisions between identifiers by providing a unique namespace for each piece of code.\n\u003cstrong\u003eEncapsulation:\u003c/strong\u003e Namespaces provide a way to encapsulate code by hiding implementation details and only exposing the public API.\n\u003cstrong\u003eModularity:\u003c/strong\u003e Namespaces provide a way to create modular code by breaking up a large codebase into smaller, more manageable pieces.\n\nWe have also defined a function called myFunction inside the namespace. The export keyword is used to make the function accessible outside the namespace.\n```\nnamespace Myself {\n    export function myFunction() {\n        console.log('This is my function');\n    }\n}\nMyself.myFunction(); // Output: This is my function\n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 30  |  What is readonly type ? \u003cbr\u003e\u003cbr\u003e you can use readonly to prevent re-assignment. This is actually only a compile-time check. \n```\ntype Person = {\n     readonly name: string;\n     age: number;\n}\nconst person1: Person = {\n   name = \"John\";\n   age: 30;\n}\n// name property will not change 'cuz it was assigned to be readonly\nperson1.name = \"Sarah\"; ❌\nperson1.age = 20; ✅ \n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 31  |  How to use the `readonly` keyword on an interface? \u003cbr\u003e\u003cbr\u003e \n```\ninterface Car {\n make: string;\n model: string;\n}\nconst readonlyCar1: Readonly\u003cCar\u003e = {\n make: \"Tesla\",\n model: \"Model S\"\n};\n// This will not compile because the make property is readonly\nreadonlyCar1.make = \"Toyota\"; ❌\n// This will not compile because the model property is readonly\nreadonlyCar1.model = \"Camry\"; ❌\n\nconst car2: Car = {\n make: \"Tesla\",\n model: \"Model S\"\n};\ncar2.make = \"Toyota\"; // OK ✅\ncar2.model = \"Camry\"; // OK ✅\n```\n\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 32  |  Write down union type ? \u003cbr\u003e\u003cbr\u003e Unions are created using the | (pipe) operator, which represents a value that can have any of the types in the union. Take the following example: \n```\ntype ProductCode = number | string;\nIn this code, ProductCode can be either a string or a number. The following code will pass the type checker:\ntype ProductCode = number | string;\nconst productCodeA: ProductCode = 'this-works';\nconst productCodeB: ProductCode = 1024;\n---------------------------------------------------------------------\nconst stuff: (num | string)[] = [1, 2, 'a'];\n---------------------------------------------------------------------\ntype DayOfWeek =\n  | \"Monday\"\n  | \"Tuesday\"\n  | \"Wednesday\"\n  | \"Thursday\"\n  | \"Friday\"\n  | \"Saturday\"\n  | \"Sunday\";\n\nlet today: DayOfWeek = \"Sunday\";\n```\n\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 33  |  What is Intersection types ? \u003cbr\u003e\u003cbr\u003e You can use intersection types to create a completely new type that has all the properties of all the types being intersected together. In this example, two interfaces named student and teacher are created. Intersected type is created by using ‘\u0026’ between student and teacher. Intersected type contains all the properties of the two interfaces. An obj of intersection type is created and values are retrieved from it. We can not use a property without assigning it to the intersection type object.\n```\ninterface Student { \nstudent_id: number; \nname: string; \n} \n\ninterface Teacher { \nTeacher_Id: number; \nteacher_name: string; \n} \n\ntype intersected_type = Student \u0026 Teacher; \n\nlet obj1: intersected_type = { \nstudent_id: 3232, \nname: \"rita\", \nTeacher_Id: 7873, \nteacher_name: \"seema\", \n}; \n\nconsole.log(obj1.Teacher_Id); \nconsole.log(obj1.name);\n-------------------------------------------------------------------------------------------------\ninterface CreateArtistBioBase {\n  artistID: string;\n  thirdParty?: boolean;\n}\ntype CreateArtistBioRequest = CreateArtistBioBase \u0026 ({ html: string } | { markdown: string });\n\n// Now you can only create a request when you include\n// artistID and either html or markdown\n\nconst workingRequest: CreateArtistBioRequest = {\n  artistID: \"banksy\",\n  markdown: \"Banksy is an anonymous England-based graffiti artist...\",\n};\n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 35  |  What is Literal Types ? \u003cbr\u003e\u003cbr\u003e TypeScript's literal types allow developers to specify exact values for variables, function parameters, or properties, enhancing type safety by ensuring variables can only hold predefined values.\n```\n// Literal Types\nlet zero: 0 = 0;\nlet mood: \"Happy\" | \"Sad\" = \"Happy\";\nmood = \"Sad\";\n-------------------------------------------------------------\ntype DayOfWeek =\n  | \"Monday\"\n  | \"Tuesday\"\n  | \"Wednesday\"\n  | \"Thursday\"\n  | \"Friday\"\n  | \"Saturday\"\n  | \"Sunday\";\nlet today: DayOfWeek = \"Sunday\";\n---------------------------------------------------------------\ntype SkillLevel = \"Beginner\" | \"Intermediate\" | \"Advanced\" | \"Expert\"; // SkillLevel is Literal Types\ntype SkiSchoolStudent = {\n  name: string;\n  age: number;\n  sport: \"ski\" | \"snowboard\";\n  level: SkillLevel;\n};\n```\n\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 36  |  How will create custom type ? \u003cbr\u003e\u003cbr\u003e In TypeScript, the syntax for creating custom types is to use the type keyword followed by the type name and then an assignment to a {} block with the type properties. Take the following:\n```\ntype Programmer = {\n  name: string;\n  knownFor: string[];\n};\n\nconst ada: Programmer = {\n  name: 'Ada Lovelace',\n  knownFor: ['Mathematics', 'Computing', 'First Programmer']\n};\n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 37  |  Create a tuple ? \u003cbr\u003e\u003cbr\u003e Typically an array contains zero to many objects of a single type. TypeScript has special analysis around arrays which contain multiple types, and where the order in which they are indexed is important. These are called tuples.\n```\ntype HTTTResponse = [number, string];\nconst apiRes: HTTTResponse = [[\"200\", \"Ok\"], [\"404\", \"Not Found\"]];\n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------- ------------------------------------------------------------------------------------------------------------------------------ |\n| 38  |  What is Merging Interfaces ? \u003cbr\u003e\u003cbr\u003e At the most basic level, the merge mechanically joins the members of both declarations into a single interface with the same name.\n```\ninterface Box {\n  height: number;\n  width: number;\n}\ninterface Box {\n  scale: number;\n}\nlet box: Box = { height: 5, width: 6, scale: 10 };\n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 38  |  Can you extend interface in TypeScript? \u003cbr\u003e\u003cbr\u003e \u003cstrong\u003eInterfaces\u003c/strong\u003e in TypeScript are a powerful way to define contracts within your code and they can be extended using the extends keyword. This is one of the most straightforward methods to extend a type. \u003cbr/\u003e \u003cstrong\u003eextends\u003c/strong\u003e is used for class inheritance, allowing a class to inherit properties and methods from another class.\n```\ninterface Person {\n  name: string\n  age: number\n}\n\ninterface Employee extends Person {\n  employeeId: number\n}\n\nconst employee: Employee = {\n  name: 'John Doe',\n  age: 30,\n  employeeId: 123\n}\n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 39  |  Extends and Implements in TypeScript? \u003cbr\u003e\u003cbr\u003e \u003cstrong\u003eextends\u003c/strong\u003e is used for class inheritance, allowing a class to inherit properties and methods from another class.\u003cbr\u003e \u003cstrong\u003eimplements\u003c/strong\u003e is used for interface implementation, ensuring a class adheres to a defined contract.\n```\ninterface Product {\n    productId: string;\n}\ninterface Appliance extends Product {\n    brand: string;\n    turnOn(): void;\n}\n\nclass WashingMachine implements Appliance {\n    productId: string;\n    brand: string;\n\n    constructor(productId:string, brand: string) {\n        this.productId = productId;\n        this.brand = brand;\n    }\n\n    turnOn(): void {\n        console.log(`${this.brand} washing machine is now on. The Product id is ${this.productId}`);\n    }\n}\n\nconst myWasher = new WashingMachine('pd001', 'LG');\nmyWasher.turnOn(); // LG washing machine is now on.\n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 40  |  Type vs Interface in TypeScript? \u003cbr\u003e\u003cbr\u003e https://blog.logrocket.com/types-vs-interfaces-typescript/  \u003cbr\u003e\n```\nUnion types\n===================================================================\nUnion types allow us to describe values that can be one of several types and create unions of various primitive, literal, or complex types:\ntype Transport = 'Bus' | 'Car' | 'Bike' | 'Walk';\nUnion type can only be defined using type. There is no equivalent to a union type in an interface.\n\nMerging\n===================================================================\nwe can define an interface multiple times, and the TypeScript compiler will automatically merge these definitions into a single interface definition.\ninterface Client { \n    name: string; \n}\ninterface Client {\n    age: number;\n}\nconst harry: Client = {\n    name: 'Harry',\n    age: 41\n}\nType aliases can’t be merged in the same way. If you try to define the Clienttype more than once, an error will be thrown:\n\nExtends and intersection\n===================================================================\nAn interface can extend one or multiple interfaces. Using the extendskeyword, a new interface can inherit all the properties and methods of an existing interface while also adding new properties.\ninterface Name {\n    name: string;\n}\ninterface Person extends Name {\n    age: Number;\n}\nconst person: Person = {\n  name: 'Joe',\n  age: 28\n}\n\nTo achieve a similar result for types, we need to use an intersection operator:\ntype Name = {\n    name: string;\n}\ntype Person = Name \u0026 {\n    age: Number;\n}\nconst person: Person = {\n  name: 'Joe',\n  age: 28\n}\n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 41  |  What is the never type in TypeScript? \u003cbr\u003e\u003cbr\u003e In TypeScript, the never type is used to specify the types that do not occur. It is mostly used to represent the functions that do not return any type of value after execution of the code written inside it. \n```\nThis example displays the throwCustomError function that when called gives an Error and does not return any output and the program ends.\n\nfunction throwCustomError(message: string): never {\n    throw new Error(message);\n}\nfunction processResult(result: string | null): string {\n    if (result === null) {\n        // This function throws an error, \n        // so the next line is unreachable.\n        throwCustomError(\u0026quot;Result is null.\u0026quot;);\n    }\n    return result;\n}\nconst result = processResult(\u0026quot;Hello GeeksforGeeks!\u0026quot;);\nconsole.log(result);\n```\n| No. | Questions                                                                                                                                                         |\n| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 41  |  Statically typed language vs Dynamically typed language? \u003cbr\u003e\u003cbr\u003e \u003cstrong\u003eStatically typed languages\u003c/strong\u003e : A language is statically typed if the type of a variable is known at compile time. For some languages this means that you as the programmer must specify what type each variable is; other languages (e.g.: Java, C, C++) offer some form of type inference, the capability of the type system to deduce the type of a variable (e.g.: OCaml, Haskell, Scala, Kotlin). The main advantage here is that all kinds of checking can be done by the compiler, and therefore a lot of trivial bugs are caught at a very early stage. Examples: C, C++, Java, Rust, Go, Scala \u003cbr/\u003e \u003cstrong\u003eDynamically typed languages\u003c/strong\u003e : A language is dynamically typed if the type is associated with run-time values, and not named variables/fields/etc. This means that you as a programmer can write a little quicker because you do not have to specify types every time (unless using a statically-typed language with type inference). Examples: Perl, Ruby, Python, PHP, JavaScript, Erlang. Most scripting languages have this feature as there is no compiler to do static type-checking anyway, but you may find yourself searching for a bug that is due to the interpreter misinterpreting the type of a variable. Luckily, scripts tend to be small so bugs have not so many places to hide. Most dynamically typed languages do allow you to provide type information, but do not require it. One language that is currently being developed, Rascal, takes a hybrid approach allowing dynamic typing within functions but enforcing static typing for the function signature.\n| 42  |  Realtime implementation of TypeScript? \u003cbr\u003e\u003cbr\u003e \u003cstrong\u003eindex.t.ds of Axios package :\u003c/strong\u003e https://stackblitz.com/edit/vitejs-vite-npgtjgrk?file=src%2Fmain.ts,node_modules%2Faxios%2Findex.d.ts\n```\nindex.t.ds\n-----------------------------------------------\nindex = you guess it right\nd = declaration\nts = typescript\n\nA helper file if you will, it describes the types of functions, classes, variables, objects, exported by a module written in JavaScript. There s no logic, no code to be executed.\nWhat is it used for? To improve type safety in codes, provide intelli-sense(autocompletion), and we can also easily transition from JavaScript to TypeScript that way.\nIn short, it describes a shape of a module (a JavaScript file), used for type checking. \n.d.ts files are therefore strict blueprints which represent the types that your source code can use.\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpiyalidas10%2Ftypescript-interview-questions-answers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpiyalidas10%2Ftypescript-interview-questions-answers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpiyalidas10%2Ftypescript-interview-questions-answers/lists"}