Top 30 typescript Interview Questions and Answers for 2024 .

Top 30 typescript Interview Questions and Answers for 2024 .

30 TypeScript Interview Questions and Answers: Boost Your 2024 Job !

Basic:

1. What is TypeScript and how does it differ from JavaScript?
2. How do you install TypeScript?
3. What is a type annotation in TypeScript?
4. Explain the difference between interfaces and classes in TypeScript.
5. What is a union type in TypeScript?
6. How do you compile TypeScript code?
7. What are the benefits of using TypeScript?
8. What is a tuple in TypeScript?
9. How do you declare an array in TypeScript?
10. What is a type assertion in TypeScript?

Intermediate:

11. Explain the concept of generics in TypeScript.
12. How do you define an optional property in TypeScript?
13. What are access modifiers in TypeScript and how do they work?
14. How does TypeScript handle null and undefined?
15. What is an enum in TypeScript and when would you use it?
16. Explain the concept of modules in TypeScript.
17. How do you implement inheritance in TypeScript?
18. What is the “readonly” modifier in TypeScript?
19. How do you declare function types in TypeScript?
20. What is the difference between “const” and “readonly” in TypeScript?

Advanced:

21. What are conditional types in TypeScript?
22. How do you create decorators in TypeScript?
23. Explain the concept of type guards in TypeScript.
24. What are mapped types in TypeScript?
25. How do you create intersection types in TypeScript?
26. Explain the “keyof” operator in TypeScript.
27. What is the “never” type in TypeScript and when is it used?
28. How do you use type inference in TypeScript?
29. What are the differences between type and interface in TypeScript?
30. Explain the concept of declaration merging in TypeScript.

Basic typescript Interview Questions: –

1. What is TypeScript and how does it differ from JavaScript?


– TypeScript is a superset of JavaScript that adds optional static typing and other features to the language. It allows developers to write and maintain large-scale JavaScript applications more easily by providing tools for catching errors and improving code quality through type checking.

2. How do you install TypeScript?


– You can install TypeScript globally via npm (Node Package Manager) by running the following command in your terminal:

npm install -g typescript

3. What is a type annotation in TypeScript?


– A type annotation in TypeScript is used to explicitly specify the type of a variable, parameter, or return value. It follows the variable or function name and is preceded by a colon (:). For example:

let age: number = 25;
function greet(name: string): void {
console.log("Hello, " + name);
}

4. Explain the difference between interfaces and classes in TypeScript.


– Interfaces:

Interfaces in TypeScript are used to define the structure of objects. They are purely for declaration and do not provide an implementation. Interfaces can be used to enforce a contract on classes or objects to ensure that they have certain properties or methods.

interface Person {
name: string;
age: number;
greet(): void;
}

– Classes:

Classes in TypeScript are used to create objects that have both data and behavior. They can implement interfaces and inherit from other classes. Classes can have constructors, properties, and methods.

class Student implements Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): void {
console.log("Hello, my name is " + this.name);
}
}

5. What is a union type in TypeScript?


– A union type in TypeScript allows a variable to have multiple types. It is denoted by the vertical bar (|) between the types. This enables flexibility in accepting different types of values.

let age: number | string;
age = 25; // valid
age = "twenty-five"; // valid

6. How do you compile TypeScript code?


TypeScript code is compiled using the `tsc` command-line tool, which stands for TypeScript Compiler. First, you need to install TypeScript globally using npm:

npm install -g typescript

Then, you can compile a TypeScript file like this:

tsc yourfile.ts

This will generate a JavaScript file with the same name (`yourfile.js`) in the same directory.

7. What are the benefits of using TypeScript?


TypeScript offers several benefits over JavaScript:


– Static Typing: Helps catch errors during development.
– Enhanced IDE Support: Provides better code completion, refactoring, and navigation.
– Readability and Maintainability: Type annotations make code more understandable and maintainable.
– Code Scalability: Suitable for large projects, thanks to its static typing and object-oriented features.

8. What is a tuple in TypeScript?


A tuple in TypeScript is an array-like structure where each element can have a different type. Tuples are defined using square brackets `[]` and type annotations for each element. For example:

let myTuple: [number, string];
myTuple = [10, "Hello"];

9. How do you declare an array in TypeScript?


Arrays in TypeScript are declared similarly to arrays in JavaScript, but you can specify the type of elements that the array will contain. For example:

let myArray: number[] = [1, 2, 3, 4, 5];

Or you can use the `Array` generic type:

let myArray: Array<number> = [1, 2, 3, 4, 5];

10. What is a type assertion in TypeScript?


Type assertion is a way to tell the TypeScript compiler about the type of a variable, overriding the compiler’s inference. It’s like a type cast in other languages, but it doesn’t perform any special checking or restructuring of data. Type assertions are done using the `<Type>` syntax or `as Type` syntax. For example:

let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;

or

let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
Both `as` and `<Type>` can be used interchangeably, but `as` is the preferred syntax when using JSX.
typescript Interview Questions
Typescript Interview Questions

Intermediate  typescript Interview Questions: –

11. Generics in TypeScript


Generics in TypeScript allow you to create reusable components that can work with a variety of data types while maintaining type safety. They enable you to define placeholders for types that are specified when the component is used. Here’s an example of a generic function:

function identity<T>(arg: T): T {
return arg;
}

let output = identity<string>("hello");
// output is of type string

12. Optional Property in TypeScript


In TypeScript, you can define optional properties in interfaces and types by appending a question mark `?` after the property name. Optional properties can be present or absent when an object is instantiated. Here’s an example:

interface Person {
name: string;
age?: number; // Optional property
}

let person1: Person = { name: "John" }; // age is optional
let person2: Person = { name: "Jane", age: 25 }; // age is provided

13. Access Modifiers in TypeScript


Access modifiers in TypeScript (`public`, `private`, and `protected`) control the visibility of class members. They determine how those members can be accessed from outside the class. Here’s how they work:

class Car {
private speed: number;

constructor(speed: number) {
this.speed = speed;
}

accelerate() {
this.speed += 10;
}
}

let myCar = new Car(50);
// myCar.speed is not accessible here because it's private
myCar.accelerate(); // This works because accelerate() is public

14. Handling Null and Undefined in TypeScript


TypeScript has strict null checks enabled by default to prevent null and undefined errors. You can explicitly declare a type to allow or disallow null or undefined:

let x: number | null = 10;
x = null; // OK

let y: number = 20;
y = null; // Error: Type 'null' is not assignable to type 'number'

15. Enum in TypeScript


Enums in TypeScript allow you to define a set of named constants, making it easier to document intent or create a set of distinct cases. They can be numeric or string-based. Here’s an example:

enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}

let playerDirection: Direction = Direction.Up;
console.log(playerDirection); // Output: UP

Enums are useful when you have a fixed set of values that a variable can take, like directions or days of the week.

16. Modules in TypeScript


Modules in TypeScript provide a way to organize code into separate files and namespaces. They help in maintaining code scalability and reusability.

// moduleA.ts
export const someVariable = 10;

// moduleB.ts
import { someVariable } from './moduleA';
console.log(someVariable); // Outputs: 10

17. Inheritance in TypeScript


In TypeScript, you can implement inheritance using the `extends` keyword to create a subclass (child class) that inherits properties and methods from a superclass (parent class).


class Animal {name: string;constructor(name: string) {this.name = name;}move(distance: number = 0) {console.log(`${this.name} moved ${distance} meters`);}}class Dog extends Animal {bark() {console.log('Woof! Woof!');}}

const dog = new Dog('Buddy');dog.move(10); // Outputs: Buddy moved 10 metersdog.bark(); // Outputs: Woof! Woof!

18. The “readonly” Modifier in TypeScript


The `readonly` modifier in TypeScript is used to make properties of an object immutable after their declaration or initialization.

class Person {
readonly name: string;
constructor(name: string) {
this.name = name;
}
}

const person = new Person('Alice');
person.name = 'Bob'; // Error: Cannot assign to 'name' because it is a read-only property

19. Declaring Function Types in TypeScript


You can declare function types in TypeScript using the arrow function syntax or the traditional function syntax.

// Arrow function syntax
let add: (x: number, y: number) => number;
add = (x, y) => x + y;

// Traditional function syntax
let subtract: (x: number, y: number) => number;
subtract = function(x, y) {
return x - y;
};

20. Difference between “const” and “readonly” in TypeScript


– `const` is used to declare constants, which are immutable variables.
– `readonly` is used to make properties of an object immutable after their initialization.

const PI = 3.14;
PI = 3.14159; // Error: Cannot assign to 'PI' because it is a constant

class Circle {
readonly radius: number;
constructor(radius: number) {
this.radius = radius;
}
}

const circle = new Circle(5);
circle.radius = 10; // Error: Cannot assign to 'radius' because it is a read-only property

Advanced  typescript Interview Questions: –

21. Conditional Types in TypeScript


Conditional types in TypeScript allow you to create types that depend on a condition. They are often used in conjunction with generic types to provide different typings based on the types passed as parameters.

type NonNullable<T> = T extends null | undefined ? never : T;

type MyType = NonNullable<string | null>; // MyType is 'string'

22. Creating Decorators in TypeScript


Decorators are a design pattern in TypeScript that allows you to attach metadata to classes, methods, or properties. They are created using the `@` syntax and can be applied to various targets.

function MyDecorator(target: any, propertyKey: string) {
console.log(`Decorating ${propertyKey} on ${target.constructor.name}`);
}

class MyClass {
@MyDecorator
myMethod() {
// Method logic here
}
}

23. Type Guards in TypeScript


Type guards are expressions that TypeScript uses to narrow down the type of a variable within a conditional block. They are typically used with `typeof`, `instanceof`, or custom type predicates to refine the type of a variable.

function isNumber(x: any): x is number {
return typeof x === "number";
}

let value: number | string = 5;

if (isNumber(value)) {
// value is now inferred as number
console.log(value.toFixed(2));
} else {
// value is inferred as string
console.log(value.toUpperCase());
}
typescript Interview Questions
Typescript Interview Questions

24. Mapped Types in TypeScript ( typescript Interview Questions )


Mapped types in TypeScript allow you to create new types based on the properties of an existing type. They are particularly useful for creating new types by transforming the properties of another type.

type Optional<T> = {
[P in keyof T]?: T[P];
};

interface Person {
name: string;
age: number;
}

type OptionalPerson = Optional<Person>;
// OptionalPerson is equivalent to { name?: string; age?: number; }

25. Creating Intersection Types in TypeScript


Intersection types in TypeScript allow you to combine multiple types into one. The resulting type will have all the properties and methods of each of the constituent types.

interface Printable {
print: () => void;
}

interface Loggable {
log: () => void;
}

function createLoggerAndPrinter(): Printable & Loggable {
return {
print() {
console.log("Printing...");
},
log() {
console.log("Logging...");
},
};
}

const loggerPrinter = createLoggerAndPrinter();
loggerPrinter.print();
loggerPrinter.log();

26. Explain the “keyof” operator in TypeScript:



The `keyof` operator in TypeScript is a utility type that produces a union type of all keys in a given type. It’s particularly useful when you want to operate on the keys of an object without knowing the specific shape of the object. Here’s an example:

interface Person {
name: string;
age: number;
email: string;
}

type PersonKey = keyof Person; // "name" | "age" | "email"

function getProperty(obj: Person, key: keyof Person) {
return obj[key];
}

const person: Person = {
name: "John",
age: 30,
email: "john@example.com"
};

const name = getProperty(person, "name"); // OK
const invalidKey = getProperty(person, "invalidKey"); // Error: Argument of type '"invalidKey"' is not assignable to parameter of type '"name" | "age" | "email"'


27. What is the “never” type in TypeScript and when is it used:

The `never` type represents the type of values that never occur. It is used to indicate that a function will not return normally, either by throwing an error or by entering an infinite loop. It is also used as the return type for functions that always throw exceptions. Here’s an example:

function throwError(message: string): never {
throw new Error(message);
}

function infiniteLoop(): never {
while (true) {
// do something indefinitely
}
}

// This function never returns
function unreachable(): never {
return throwError("This function should never return");
}

28. How do you use type inference in TypeScript: ( typescript Interview Questions )



Type inference in TypeScript allows the compiler to automatically determine the types of variables based on their initialization values. You can use type inference by simply initializing variables without explicitly specifying their types. Here’s an example:

let x = 10; // TypeScript infers x to be of type number
let y = "hello"; // TypeScript infers y to be of type string

function add(a: number, b: number) {
return a + b;
}

const result = add(x, 5); // TypeScript infers result to be of type number


29. What are the differences between type and interface in TypeScript:



In TypeScript, both `type` and `interface` can be used to define custom types, but there are some differences between them: ( typescript Interview Questions )

– `interface` can be used to describe object shapes, while `type` can be used to create aliases for any type including primitives, unions, intersections, etc.
– `interface` can be augmented using declaration merging, while `type` cannot.
– `type` supports intersections and unions directly, while `interface` can only extend other `interface`s or `class`es.

Here’s an example showcasing these differences:

// Using interface
interface Point {
x: number;
y: number;
}

interface Point {
z: number;
}

const point: Point = { x: 1, y: 2, z: 3 }; // OK

// Using type alias
type Coordinate = {
x: number;
y: number;
};

type Coordinate = {
z: number;
}; // Error: Duplicate identifier 'Coordinate'

const coordinate: Coordinate = { x: 1, y: 2, z: 3 };

30. Explain the concept of declaration merging in TypeScript:



Declaration merging in TypeScript refers to the process where the compiler merges multiple declarations with the same name into a single declaration. This feature allows you to spread the definition of a single entity across multiple locations. Declaration merging is applicable to interfaces, namespaces, classes, and enums. Here’s an example:

interface Car {
brand: string;
model: string;
}

interface Car {
year: number;
}

const myCar: Car = {
brand: "Toyota",
model: "Camry",
year: 2022
};

In this example, TypeScript merges the two `Car` interface declarations into a single `Car` interface with properties `brand`, `model`, and `year`.

Also read: Top 50 Angular Interview Questions And Answers For 2024

Leave a Reply

Your email address will not be published. Required fields are marked *