Typescript Interview Questions
TypescriptInterview Questions for Freshers
- What are the primitive types in TypeScript?
- Explain how the arrays work in TypeScript.
- What is any type, and when to use it?
- What is void, and when to use the void type?
- What is an unknown type, and when to use it in TypeScript?
- What are the different keywords to declare variables in TypeScript?
- Provide the syntax of a function with the type annotations.
- How to create objects in TypeScript?
- How to specify optional properties in TypeScript?
- Explain the concept of null and its use in TypeScript.
- What is undefined in TypeScript?
- Explain the purpose of the never type in TypeScript.
- Explain how enums work in TypeScript?
- What is the typeof operator? How is it used in TypeScript?
- What are the rest parameters and arguments in TypeScript?
- What is parameter destructuring?
- Explain the TypeScript class syntax.
- Explain the arrow function syntax in TypeScript.
- Provide the syntax for optional parameters in TypeScript.
- What is the purpose of the tsconfig.json file?
TypescriptInterview Questions for Experienced
- Explain the different variants of the for loop in TypeScript.
- Explain the symbol type in TypeScript.
- Explain how optional chaining works in TypeScript.
- Provide the TypeScript syntax to create function overloads.
- What is meant by type inference?
- What is meant by contextual typing?
- What is the purpose of noImplicitAny?
- What is an interface?
- Explain the various ways to control member visibility in TypeScript.
- Does TypeScript support static classes? If not, why?
- What are abstract classes? When should you use one?
- What are anonymous functions? Provide their syntax in TypeScript.
- What are union types in TypeScript?
- What are intersection types?
- What are type aliases? How do you create one?
- Explain the tuple types in TypeScript.
- Explain how tuple destructuring works in TypeScript.
- What are type assertions in TypeScript?
- How to enforce strict null checks in TypeScript?
- How to make object properties immutable in TypeScript? (hint: readonly)
TypescriptInterview Questions for Experienced
- What is a type declaration file?
- What are triple-slash directives?
- Explain the purpose of the ‘in’ operator.
- What are the ‘implements’ clauses in TypeScript?
- What are string literal types?
- What are template literal types?
- Explain the concept of inheritance in TypeScript.
- What are conditional types? How do you create them?
- What is the Function type in TypeScript?
- List some of the utility types provided by TypeScript and explain their usage.
Answers:
1.What are the primitive types in TypeScript?
The primitive types in TypeScript are:
- string
- number
- boolean
- null
- undefined
- symbol
- bigint
- Explain how the arrays work in TypeScript.
In TypeScript, arrays can be defined using two syntaxes:- Using square brackets:
let arr: number[] = [1, 2, 3]; - Using the Array generic type:
let arr: Array<number> = [1, 2, 3];
- Using square brackets:
- What is any type, and when to use it?
Theanytype in TypeScript is a type that can hold any value. It is used when you want to opt-out of type checking for a particular variable. It is useful when dealing with dynamic content or when migrating JavaScript code to TypeScript. - What is void, and when to use the void type?
Thevoidtype in TypeScript represents the absence of a value. It is commonly used as the return type of functions that do not return a value. - What is an unknown type, and when to use it in TypeScript?
Theunknowntype in TypeScript is a type-safe counterpart ofany. It represents any value, but unlikeany, you cannot perform operations on anunknowntype without first asserting or narrowing its type. It is used when you want to accept any value but still want to enforce type safety. - What are the different keywords to declare variables in TypeScript?
The different keywords to declare variables in TypeScript are:let: for block-scoped variables that can be reassigned.const: for block-scoped variables that cannot be reassigned.var: for function-scoped variables (not recommended in modern TypeScript).
- Provide the syntax of a function with the type annotations.
The syntax of a function with type annotations in TypeScript is as follows:function functionName(param1: type1, param2: type2): returnType {// function body} - How to create objects in TypeScript?
Objects in TypeScript can be created using object literals or by defining interfaces or classes. Example of an object literal:let person: { name: string; age: number } = {name: "John",age: 30}; - How to specify optional properties in TypeScript?
Optional properties in TypeScript can be specified using the?symbol after the property name in an interface or type definition. Example:interface Person {name: string;age?: number; // optional property} - Explain the concept of null and its use in TypeScript.
In TypeScript,nullis a primitive value that represents the intentional absence of any object value. It is used to indicate that a variable does not have a value. TypeScript has strict null checking, which helps prevent null reference errors. - What is undefined in TypeScript?
undefinedis a primitive value in TypeScript that indicates that a variable has not been assigned a value. It is the default value of uninitialized variables. - Explain the purpose of the never type in TypeScript.
Thenevertype in TypeScript represents values that never occur. It is used for functions that always throw an error or never return (e.g., infinite loops). It indicates that a function does not have a reachable endpoint. - Explain how enums work in TypeScript?
Enums in TypeScript are a way to define a set of named constants. They can be numeric or string-based. Enums help improve code readability and maintainability by providing meaningful names for sets of related values. Example of a numeric enum:enum Direction {Up,Down,Left,Right} - What is the typeof operator? How is it used in TypeScript?
Thetypeofoperator in TypeScript is used to obtain the type of a variable or expression at runtime. It returns a string indicating the type of the operand. It is commonly used in type guards to narrow down types. - What are the rest parameters and arguments in TypeScript?
Rest parameters in TypeScript allow a function to accept an indefinite number of arguments as an array. They are defined using the...syntax. Example:function sum(...numbers: number[]): number {return numbers.reduce((acc, curr) => acc + curr, 0);} - What is parameter destructuring?
Parameter destructuring in TypeScript allows you to extract values from objects or arrays directly in the function parameters. This makes it easier to work with complex data structures. Example:function greet({ name, age }: { name: string; age: number }) {console.log(`Hello, my name is ${name} and I am ${age} years old.`);} - Explain the TypeScript class syntax.
The TypeScript class syntax is similar to JavaScript classes but includes type annotations for properties and methods. Classes can have constructors, methods, and access modifiers (public, private, protected). Example:class Person {private name: string;constructor(name: string) {this.name = name;}greet(): void {console.log(`Hello, my name is ${this.name}`);}} - Explain the arrow function syntax in TypeScript.
Arrow functions in TypeScript have a concise syntax and lexically bind thethisvalue. They are defined using the=>syntax. Example:const add = (a: number, b: number): number => {return a + b;}; - Provide the syntax for optional parameters in TypeScript.
Optional parameters in TypeScript are defined by adding a?after the parameter name in the function signature. Example:function greet(name: string, age?: number): void {if (age) {console.log(`Hello, my name is ${name} and I am ${age} years old.`);} else {console.log(`Hello, my name is ${name}.`);}} - What is the purpose of the tsconfig.json file?
Thetsconfig.jsonfile in TypeScript is used to configure the TypeScript compiler options for a project. It specifies the root files and the compiler options required to compile the project. It helps manage settings like target ECMAScript version, module system, strictness options, and more.
TypescriptInterview Questions for Experienced
- Explain the different variants of the for loop in TypeScript.
TypeScript supports several variants of the for loop:- Traditional for loop:
for (let i = 0; i < 10; i++) { } - for…in loop: Iterates over the keys of an object.
for (let key in obj) { } - for…of loop: Iterates over the values of an iterable object (like arrays).
for (let value of array) { }
- Traditional for loop:
- Explain the symbol type in TypeScript.
Thesymboltype in TypeScript represents a unique and immutable primitive value. Symbols are often used as keys for object properties to avoid name collisions. - Explain how optional chaining works in TypeScript.
Optional chaining in TypeScript allows you to safely access nested properties of an object without having to check for null or undefined values at each level. It uses the?.operator. Example:let user = {address: {street: "123 Main St"}};let street = user?.address?.street; // "123 Main St"let city = user?.address?.city; // undefined - Provide the TypeScript syntax to create function overloads.
Function overloads in TypeScript allow you to define multiple signatures for a single function. The implementation must match one of the signatures. Example:function add(a: number, b: number): number;function add(a: string, b: string): string;function add(a: any, b: any): any {return a + b;} - What is meant by type inference?
Type inference in TypeScript is the ability of the compiler to automatically deduce the type of a variable based on its value or usage, without explicit type annotations. - What is meant by contextual typing?
Contextual typing in TypeScript refers to the process where the type of a variable is inferred based on the context in which it is used, such as function parameters or return types. - What is the purpose of noImplicitAny?
ThenoImplicitAnycompiler option in TypeScript is used to prevent variables from being implicitly assigned theanytype. When enabled, it forces developers to explicitly declare types, improving type safety. - What is an interface?
An interface in TypeScript is a way to define the shape of an object. It specifies the properties and methods that an object must have, allowing for type checking and code organization. Example:interface Person {name: string;age: number;greet(): void;} - Explain the various ways to control member visibility in TypeScript.
In TypeScript, member visibility can be controlled using access modifiers:public: Members are accessible from anywhere (default).private: Members are accessible only within the class.protected: Members are accessible within the class and its subclasses.
- Does TypeScript support static classes? If not, why?
TypeScript does not support static classes in the same way some other languages do. However, you can create a class with only static members by using thestatickeyword for properties and methods. This approach allows you to group related static functionality without instantiating the class. - What are abstract classes? When should you use one?
Abstract classes in TypeScript are classes that cannot be instantiated directly and are meant to be subclassed. They can contain abstract methods (without implementation) that must be implemented by derived classes. Use abstract classes when you want to define a common base class with shared functionality and enforce a contract for subclasses. - What are anonymous functions? Provide their syntax in TypeScript.
Anonymous functions in TypeScript are functions that do not have a name. They are often used as arguments to other functions or assigned to variables. The syntax is similar to regular functions but without a name. Example:let add = function(a: number, b: number): number {return a + b;}; - What are union types in TypeScript?
Union types in TypeScript allow a variable to hold values of multiple types. They are defined using the|operator. Example:let value: string | number;value = "Hello"; // validvalue = 42; // valid - What are intersection types?
Intersection types in TypeScript allow you to combine multiple types into one. A variable of an intersection type must satisfy all the combined types. They are defined using the&operator. Example:interface A {propA: string;}interface B {propB: number;}type C = A & B;let obj: C = { propA: "Hello", propB: 42 }; - What are type aliases? How do you create one?
Type aliases in TypeScript allow you to create a new name for a type. They are created using thetypekeyword. Example:type StringOrNumber = string | number;let value: StringOrNumber;value = "Hello"; // validvalue = 42; // valid - Explain the tuple types in TypeScript.
Tuple types in TypeScript are used to define an array with a fixed number of elements, where each element can have a different type. They are defined using square brackets with specified types for each position. Example:let tuple: [string, number, boolean] = ["Hello", 42, true]; - Explain how tuple destructuring works in TypeScript.
Tuple destructuring in TypeScript allows you to extract values from a tuple into individual variables. Example:let tuple: [string, number] = ["Hello", 42];let [greeting, age] = tuple;console.log(greeting); // "Hello"console.log(age); // 42 - What are type assertions in TypeScript?
Type assertions in TypeScript allow you to override the inferred type of a variable and specify a different type. They are similar to type casting in other languages and can be done using theaskeyword or angle bracket syntax. Example:let someValue: any = "Hello, TypeScript!";let strLength: number = (someValue as string).length; - How to enforce strict null checks in TypeScript?
To enforce strict null checks in TypeScript, you can enable thestrictNullChecksoption in thetsconfig.jsonfile. When this option is enabled, TypeScript will treatnullandundefinedas distinct types and will require explicit handling of these values. Exampletsconfig.jsonsetting:{"compilerOptions": {"strictNullChecks": true}} - How to make object properties immutable in TypeScript? (hint: readonly)
To make object properties immutable in TypeScript, you can use thereadonlymodifier when defining the properties in an interface or class. This prevents the properties from being reassigned after their initial assignment. Example:interface Person {readonly name: string;readonly age: number;}let person: Person = { name: "John", age: 30 };// person.name = "Doe"; // Error: Cannot assign to 'name' because it is a read-only property.
TypescriptInterview Questions for Experienced
- What is a type declaration file?
A type declaration file in TypeScript is a file with a.d.tsextension that contains type information about JavaScript code. It allows TypeScript to understand the types of variables, functions, and classes defined in JavaScript libraries, enabling type checking and IntelliSense support. - What are triple-slash directives?
Triple-slash directives in TypeScript are single-line comments that contain a special instruction for the compiler. They are used to include additional files or reference type declaration files. The syntax is/// <reference path="..." />. - Explain the purpose of the ‘in’ operator.
Theinoperator in TypeScript is used to check if a property exists in an object. It returnstrueif the specified property is found in the object, andfalseotherwise. Example:let person = { name: "John", age: 30 };console.log("name" in person); // trueconsole.log("address" in person); // false - What are the ‘implements’ clauses in TypeScript?
Theimplementsclause in TypeScript is used in class declarations to indicate that a class adheres to a specific interface. It ensures that the class provides implementations for all the properties and methods defined in the interface. Example:interface Person {name: string;greet(): void;}class Student implements Person {name: string;constructor(name: string) {this.name = name;}greet(): void {console.log(`Hello, my name is ${this.name}`);}} - What are string literal types?
String literal types in TypeScript allow you to specify that a variable or parameter can only hold a specific string value or a set of specific string values. They are defined using string literals. Example:type Direction = "Up" | "Down" | "Left" | "Right";let move: Direction;move = "Up"; // validmove = "Forward"; // Error: Type '"Forward"' is not assignable to type 'Direction'. - What are template literal types?
Template literal types in TypeScript allow you to create new string types by combining string literals and other types using template literal syntax. They enable more complex string type definitions. Example:type Greeting = `Hello, ${string}!`;let greet: Greeting;greet = "Hello, TypeScript!"; // validgreet = "Hi, TypeScript!"; // Error: Type '"Hi, TypeScript!"' is not assignable to type 'Greeting'. - Explain the concept of inheritance in TypeScript.
Inheritance in TypeScript allows a class to extend another class, inheriting its properties and methods. The derived class can also add its own properties and methods or override those of the base class. This promotes code reuse and establishes a hierarchical relationship between classes. Example:class Animal {speak(): void {console.log("Animal speaks");}}class Dog extends Animal {speak(): void {console.log("Dog barks");}} - What are conditional types? How do you create them?
Conditional types in TypeScript allow you to define types based on a condition. They use the syntaxT extends U ? X : Y, where if typeTextends typeU, the resulting type isX; otherwise, it isY. Example:type IsString<T> = T extends string ? "Yes" : "No";type Result1 = IsString<string>; // "Yes"type Result2 = IsString<number>; // "No" - What is the Function type in TypeScript?
TheFunctiontype in TypeScript represents the type of all functions. It is a built-in type that can be used to type variables or parameters that are expected to be functions. However, it is generally recommended to use more specific function types with defined parameter and return types for better type safety. - List some of the utility types provided by TypeScript and explain their usage. Some of the utility types provided by TypeScript include:
Partial<T>: Constructs a type with all properties ofTset to optional.Required<T>: Constructs a type with all properties ofTset to required.Readonly<T>: Constructs a type with all properties ofTset to readonly.Pick<T, K>: Constructs a type by picking a set of propertiesKfrom typeT.Omit<T, K>: Constructs a type by omitting a set of propertiesKfrom typeT.Record<K, T>: Constructs a type with a set of propertiesKof typeT.Exclude<T, U>: Constructs a type by excluding fromTall properties that are assignable toU.Extract<T, U>: Constructs a type by extracting fromTall properties that are assignable toU. These utility types help in transforming and manipulating types, making it easier to work with complex type definitions in TypeScript.