InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
List some of the utility types provided by TypeScript and explain their usage. |
||||||||||
|
Answer» TYPESCRIPT PROVIDES various utility types that make common TYPE transformations easy. These utility types are available globally. Here are some of the essential utility types included in TypeScript.
|
|||||||||||
| 2. |
What is the Function type in TypeScript? |
|
Answer» FUNCTION is a global type in TypeScript. It has PROPERTIES like bind, CALL, and apply, ALONG with the other properties present on all function values. function perform(fn: Function) {fn(10);}You can always call a value of the Function type, and it returns a value of ‘any’ type. |
|
| 3. |
What are conditional types? How do you create them? |
|
Answer» A conditional type ALLOWS you to DYNAMICALLY select one of two POSSIBLE types based on a CONDITION. The condition is expressed as a type relationship test. C extends B ? TypeX : TypeYHere, if type C extends B, the value of the above type is TypeX. Otherwise, it is TypeY. |
|
| 4. |
Explain the concept of inheritance in TypeScript. |
|
Answer» Inheritance ALLOWS a class to extend ANOTHER class and reuse and modify the BEHAVIOR defined in the other class. The class which inherits another class is CALLED the derived class, and the class getting inherited is called the base class. In TypeScript, a class can only extend one class. TypeScript USES the keyword ‘extends’ to specify the relationship between the base class and the derived classes. class Rectangle {length: number;breadth: numberconstructor(length: number, breadth: number) { this.length = length; this.breadth = breadth}area(): number { return this.length * this.breadth;}}class Square extends Rectangle {constructor(side: number) { super(side, side);}volume() { return "Square doesn't have a volume!"}}const sq = new Square(10);console.log(sq.area()); // 100console.log(sq.volume()); // "Square doesn't have a volume!"In the above example, because the class Square extends functionality from Rectangle, we can create an instance of square and call both the area() and volume() methods. |
|
| 5. |
What are template literal types? |
|
Answer» Template literal types are similar to the string literal types. You can combine them with concrete, literal types to produce a new string literal type. Template literal types allow us to use the string literal types as BUILDING blocks to create new string literal types. type Point = "GraphPoint";// type Shape = "Grid GraphPoint"type Shape = `Grid ${Point}`;Template literal types can also expand into multiple STRINGS via unions. It helps us create the SET of every POSSIBLE string literal that each union member can represent. type Color = "green" | "yellow";type Quantity = "five" | "SIX";// type ItemTwo = "five item" | "six item" | "green item" | "yellow item"type ItemOne = `${Quantity | Color} item`; |
|
| 6. |
What are string literal types? |
|
Answer» In TypeScript, you can refer to SPECIFIC strings and numbers as types. let FOO: "bar" = "bar";// OKfoo = "bar";// Error: Type '"baz"' is not assignable to type '"bar"'.(2322)foo = "baz";String literal types on their own are not that useful. However, you can combine them into unions. This allows you to specify all the string values that a variable can take, in turn acting like enums. This can be useful for function parameters. function greet(name: string, GREETING: "hi" | "hello" | "HOLA") {// ...}greet("John", "hello");// Error: Argument of type '"Howdy?"' is not assignable to PARAMETER of type '"hi" | "hello" | "hola"'.(2345)greet("Mary", "Howdy?");String literal types can help us spell-check the string values. |
|
| 7. |
What are the ‘implements’ clauses in TypeScript? |
|
Answer» An implements clause is used to check that a class satisfies the contract specified by an interface. If a class implements an interface and doesn’t IMPLEMENT that interface, the TypeScript compiler issues an error. interface Runnable {run(): void;}class Job implements Runnable {run() { console.log("RUNNING the scheduled job!");}}// Class 'Task' incorrectly implements interface 'Runnable'.// Property 'run' is missing in type 'Task' but required in type 'Runnable'.(2420)class Task implements Runnable {PERFORM() { console.log("pong!");}}A class can implement more than ONE interface. In this case, the class has to specify all the contracts of those interfaces. |
|
| 8. |
Explain the purpose of the ‘in’ operator. |
|
Answer» The in operator is used to find if a PROPERTY is in the specified object. It RETURNS true if the property belongs to the object. OTHERWISE, it returns false. const CAR = { make: 'Hyundai', model: 'Elantra', year: 2017 };console.log('model' in car); // trueconsole.log('test' in car); // false |
|
| 9. |
What are triple-slash directives? |
|
Answer» Triple-slash directives are single-line comments that contain a single XML tag. TypeScript uses this XML tag as a compiler directive. You can only place a triple-slash directive at the top of the containing file. Only single or multi-line comments can come before a triple-slash directive. TypeScript treats them as regular comments if it occurs in the middle of a code block, after a statement. The primary USE of triple-slash directives is to include other files in the compilation process. For EXAMPLE, the following directive instructs the compiler to include a file specified by the path in the containing TypeScript file. /// <REFERENCE path="..." /> Triple-slash directives also ORDER the output when using --out or --outFile. The output files are produced to the output file location in the same order as the input files. |
|
| 10. |
What is a type declaration file? |
|
Answer» A typical TypeScript project references other third-party TypeScript libraries such as JQUERY to perform routine TASKS. Having type information for the library code helps you in coding by providing detailed information about the types, method signatures, etc., and provides IntelliSense. A type declaration file is a text file ENDING with a .d.ts EXTENSION providing a way to declare the existence of some types or values without actually providing IMPLEMENTATIONS for those values. It contains the type declarations but doesn’t have any source code. It doesn’t produce a .js file after compilation. |
|
| 11. |
How to make object properties immutable in TypeScript? (hint: readonly) |
|
Answer» You can mark object properties as immutable by using the readonly keyword before the property NAME. For example: interface Coordinate {readonly x: NUMBER;readonly y: number;}When you mark a property as readonly, it can only be set when you initialize the object. Once the object is created, you cannot change it. let c: Coordinate = { x: 5, y: 15 };c.x = 20; // Cannot assign to 'x' because it is a read-only property.(2540) |
|
| 12. |
How to enforce strict null checks in TypeScript? |
|
Answer» Null pointers are ONE of the most common sources of unexpected runtime errors in programming. TYPESCRIPT HELPS you avoid them to a large degree by enforcing strict null checks. You can enforce strict null checks in two ways:
When the flag is false, TypeScript IGNORES null and undefined values in the code. When it is true, null and undefined have their distinct types. The compiler throws a type error if you try to use them where a concrete value is expected. |
|
| 13. |
What are type assertions in TypeScript? |
|
Answer» Sometimes, you as a programmer might know more about the type of a variable than TypeScript can infer. Usually, this happens when you know the type of an object is more specific than its current type. In such cases, you can tell the TypeScript compiler not to infer the type of the variable by using type assertions. TypeScript provides TWO forms to assert the types.
Type assertions are similar to TYPECASTING in other programming languages such as C# or Java. However, unlike those languages, there’s no runtime penalty of boxing and unboxing variables to fit the types. Type assertions simply let the TypeScript compiler know the type of the variable. |
|
| 14. |
Explain how tuple destructuring works in TypeScript. |
|
Answer» You can destructure tuple elements by USING the assignment operator (=). The DESTRUCTURING variables get the types of the corresponding tuple elements. let employeeRecord: [string, number] = ["JOHN Doe", 50000];let [emp_name, emp_salary] = employeeRecord;console.log(`Name: ${emp_name}`); // "Name: John Doe"console.log(`Salary: ${emp_salary}`); // "Salary: 50000"After destructuring, you can’t assign a VALUE of a different type to the destructured VARIABLE. For example, emp_name = true; // Type 'boolean' is not assignable to type 'string'.(2322) |
|
| 15. |
Explain the tuple types in TypeScript. |
|
Answer» Tuples are a special TYPE in TypeScript. They are SIMILAR to arrays with a fixed number of elements with a known type. However, the types need not be the same. // Declare a tuple type and initialize itlet values: [string, number] = ["Foo", 15];// Type 'BOOLEAN' is not assignable to type 'string'.(2322)// Type 'string' is not assignable to type 'number'.(2322)LET wrongValues: [string, number] = [true, "hello"]; // ErrorSince TypeScript 3.0, a tuple can specify one or more optional types using the ? as shown below. let values: [string, number, boolean?] = ["Foo", 15]; |
|
| 16. |
What are type aliases? How do you create one? |
|
Answer» Type aliases give a new, meaningful NAME for a type. They don’t create new TYPES but create new names that refer to that type. For example, you can alias a union type to avoid TYPING all the types everywhere that value is being used. type alphanumeric = string | number;LET value: alphanumeric = "";value = 10; |
|
| 17. |
What are intersection types? |
|
Answer» Intersection types let you combine the members of TWO or more types by using the ‘&’ operator. This allows you to combine existing types to get a SINGLE type with all the features you need. The following example creates a NEW type Supervisor that has the members of types Employee and Manager. interface Employee {WORK: () => string;}interface Manager {manage: () => string;}type Supervisor = Employee & Manager;// john can both work and managelet john: Supervisor; |
|
| 18. |
What are union types in TypeScript? |
|
Answer» A union type is a special construct in TypeScript that INDICATES that a value can be one of several types. A vertical bar (|) separates these types. Consider the FOLLOWING example where the variable value belongs to a union type consisting of strings and numbers. The value is initialized to string “Foo”. Because it can only be a string or a number, we can change it to a number later, and the TypeScript compiler doesn’t complain. let value: string | number = "Foo";value = 10; // OkayHowever, if we try to set the value to a type not included in the union types, we get the following error. value = true; // Type 'boolean' is not ASSIGNABLE to type 'string | number'.(2322)Union types allow you to create new types out of existing types. This removes a lot of BOILERPLATE CODE as you don’t have to create new classes and type hierarchies. |
|
| 19. |
What are anonymous functions? Provide their syntax in TypeScript. |
|
Answer» An anonymous function is a function without a name. Anonymous FUNCTIONS are typically used as callback functions, i.e., they are passed around to other functions, only to be invoked by the other function at a later point in time. For example, setTimeout(function () { console.log('Run after 2 seconds')}, 2000);You can invoke an anonymous function as soon as it’s created. It’s called ‘immediately invoked function execution (IIFE)’, For example:(function() { console.log('Invoked immediately after CREATION');})(); |
|
| 20. |
What are abstract classes? When should you use one? |
|
Answer» Abstract classes are similar to interfaces in that they specify a contract for the objects, and you cannot instantiate them directly. HOWEVER, unlike interfaces, an abstract class may provide implementation details for one or more of its members. An abstract class marks one or more of its members as abstract. Any classes that EXTEND an abstract class have to provide an implementation for the abstract members of the superclass. Here is an example of an abstract class WRITER with two member functions. The write() method is marked as abstract, whereas the greet() method has an implementation. Both the FictionWriter and RomanceWriter classes that extend from Writer have to provide their specific implementation for the write method. abstract class Writer {abstract write(): void;greet(): void { console.log("Hello, there. I am a writer.");}}class FictionWriter EXTENDS Writer {write(): void { console.log("WRITING a fiction.");}}class RomanceWriter extends Writer {write(): void { console.log("Writing a romance novel.");}}const john = new FictionWriter();john.greet(); // "Hello, there. I am a writer."john.write(); // "Writing a fiction."const mary = new RomanceWriter();mary.greet(); // "Hello, there. I am a writer."mary.write(); // "Writing a romance novel." |
|
| 21. |
Does TypeScript support static classes? If not, why? |
|
Answer» TypeScript doesn’t SUPPORT static classes, unlike the popular object-oriented programming LANGUAGES like C# and Java. These languages need static classes because all code, i.e., data and functions, need to be inside a class and cannot exist independently. Static classes provide a way to allow these functions without ASSOCIATING them with any OBJECTS. In TypeScript, you can create any data and functions as SIMPLE objects without creating a containing class. Hence TypeScript doesn’t need static classes. A singleton class is just a simple object in TypeScript. |
|
| 22. |
Explain the various ways to control member visibility in TypeScript. |
|
Answer» TypeScript provides three KEYWORDS to control the visibility of CLASS members, such as PROPERTIES or methods.
|
|
| 23. |
What is the purpose of noImplicitAny? |
|
Answer» Usually, when we don’t provide any type on a variable, TypeScript assumes ‘any’ type. For EXAMPLE, TypeScript compiles the following CODE, assuming the parameter ‘s’ is of any type. It WORKS as long as the caller passes a string. function PARSE(s) {console.log(s.split(' '));}parse("Hello world"); // ["Hello", "world"]However, the code breaks down as SOON as we pass a number or other type than a string that doesn’t have a split() method on it. For example, function parse(s) {console.log(s.split(' ')); // [ERR]: s.split is not a function}parse(10);noImplicitAny is a compiler option that you set in the tsconfig.json file. It forces the TypeScript compiler to raise an error whenever it infers a variable is of any type. This prevents us from accidentally causing similar errors. Parameter 's' implicitly has an 'any' type.(7006)function parse(s) {console.log(s.split(' ')); // [ERR]: s.split is not a function} |
|
| 24. |
What is meant by contextual typing? |
|
Answer» When the TypeScript compiler USES the location (or context) of a variable to infer its type, it’s called CONTEXTUAL typing. In the following example, TypeScript uses the Window.onmousedown function type information to infer the type of the function expression on the right-hand side of the assignment. This allows it to infer the type of the e parameter, which does have a button property but not a property NAMED foo. window.onmousedown = function (e) {console.log(e.button); //<- OKconsole.log(e.foo); //<- ERROR!}; |
|
| 25. |
What is meant by type inference? |
|
Answer» TypeScript can infer the type of a variable when you don’t provide an EXPLICIT type. This is KNOWN as type inference. This is usually done when the variables or parameters are INITIALIZED during the declaration. For example, TypeScript knows that the variable FOO is a string, even THOUGH we don’t mention string as a type. let foo = "this is a string";console.log(typeof foo); // "string" |
|
| 26. |
Provide the TypeScript syntax to create function overloads. |
|
Answer» Function overloading allows us to define MULTIPLE functions with the same name, as long as their number of parameters or the types of parameters are different. The following example defines TWO OVERLOADS for the function buildDate. The first overload takes a number as a parameter, whereas the SECOND takes three numbers as parameters. These are called overload signatures. The body of the function also called an implementation signature, follows the overload signatures. You can’t call this signature directly, as it’s not visible from the outside. It should be compatible with the overload signatures. function buildDate(timestamp: number): Date;function buildDate(m: number, d: number, y: number): Date;function buildDate(mOrTimestamp: number, d?: number, y?: number): Date {if (d !== undefined && y !== undefined) { return new Date(y, mOrTimestamp, d);} else { return new Date(mOrTimestamp);}}const d1 = buildDate(87654321);const d2 = buildDate(2, 2, 2); |
|
| 27. |
Explain how optional chaining works in TypeScript. |
|
Answer» Optional chaining allows you to ACCESS PROPERTIES and call methods on them in a chain-like fashion. You can do this using the ‘?.’ operator. TypeScript immediately STOPS running some expression if it runs into a ‘null’ or ‘undefined’ value and RETURNS ‘undefined’ for the entire expression chain. Using optional chaining, the following expression let x = FOO === null || foo === undefined ? undefined : foo.bar.baz();can be expressed as: let x = foo?.bar.baz(); |
|
| 28. |
Explain the symbol type in TypeScript. |
|
Answer» Symbols were introduced in ES6 and are supported by TypeScript. Similar to NUMBERS and strings, symbols are PRIMITIVE TYPES. You can use Symbols to create unique properties for objects. You can create symbol values by calling the Symbol() constructor, optionally providing a string key. LET foo = Symbol();let bar = Symbol("bar"); // optional string keyA key characteristic of symbols is that they are unique and immutable. let foo = Symbol("foo");let newFoo = Symbol("foo");let AREEQUAL = foo === newFoo;console.log(areEqual); // false, symbols are unique |
|
| 29. |
Explain the different variants of the for loop in TypeScript. |
|
Answer» TypeScript provides the FOLLOWING THREE WAYS to LOOP over collections.
|
|