TypeScript

TypeScript

Top Interview Questions

About TypeScript

 

Introduction to TypeScript

TypeScript is an open-source programming language developed and maintained by Microsoft. It is a superset of JavaScript, meaning all valid JavaScript code is also valid TypeScript code. However, TypeScript introduces additional features, primarily static typing, which helps developers catch errors early during the development process, rather than at runtime. Since its introduction in 2012, TypeScript has gained widespread popularity, especially in large-scale application development, due to its ability to make code more maintainable, readable, and scalable.

TypeScript compiles down to plain JavaScript, which means it can run on any environment that supports JavaScript, including browsers, Node.js, and other JavaScript engines. This makes TypeScript highly compatible while providing the developer with advanced features that are not available in vanilla JavaScript.


Key Features of TypeScript

  1. Static Typing:
    One of TypeScript’s core features is static typing. This allows developers to define the type of variables, function parameters, and return values. For instance, a variable can be explicitly declared as a string, number, or boolean. Static typing enables the compiler to detect errors at compile-time, which reduces runtime errors and makes debugging easier.

    let name: string = "Yash";
    let age: number = 25;
    
  2. Type Inference:
    Even if a developer does not explicitly declare a type, TypeScript can infer it based on the assigned value. This ensures a balance between type safety and developer convenience.

    let score = 100; // TypeScript infers score as number
    
  3. Interfaces:
    Interfaces in TypeScript define the structure of objects, providing contracts that objects must adhere to. They help enforce consistency across the codebase and make it easier to work in teams.

    interface Person {
        name: string;
        age: number;
    }
    
    let employee: Person = { name: "Yash", age: 25 };
    
  4. Classes and Object-Oriented Programming:
    TypeScript enhances JavaScript’s class syntax by adding features like access modifiers (public, private, protected) and abstract classes, allowing developers to write more structured and object-oriented code.

    class Employee {
        private id: number;
        public name: string;
    
        constructor(id: number, name: string) {
            this.id = id;
            this.name = name;
        }
    
        getDetails(): string {
            return `${this.name} (${this.id})`;
        }
    }
    
    let emp = new Employee(101, "Yash");
    console.log(emp.getDetails());
    
  5. Enums:
    Enums are a way to define a set of named constants, making code more readable and maintainable.

    enum Direction {
        Up,
        Down,
        Left,
        Right
    }
    
    let move: Direction = Direction.Up;
    
  6. Generics:
    Generics allow the creation of reusable components that can work with multiple types instead of a single one. This is particularly useful for data structures and functions that should handle a variety of types safely.

    function identity<T>(arg: T): T {
        return arg;
    }
    
    let output = identity<string>("Hello TypeScript");
    
  7. Modules and Namespaces:
    TypeScript supports modular programming by allowing developers to split code into multiple files and use imports and exports. This promotes code reusability and maintainability in large projects.

    // math.ts
    export function add(a: number, b: number): number {
        return a + b;
    }
    
    // main.ts
    import { add } from './math';
    console.log(add(5, 10));
    
  8. Type Aliases and Union Types:
    TypeScript allows developers to create custom types using type aliases and also supports union types to handle multiple possible types for a variable.

    type ID = string | number;
    let userId: ID = 101; // can also be a string
    

Advantages of TypeScript

  1. Early Error Detection:
    TypeScript’s static typing helps catch errors during compilation rather than at runtime. This is especially beneficial in large applications where debugging runtime errors can be complex and time-consuming.

  2. Improved Code Quality:
    With TypeScript, developers can write cleaner, more predictable code using features like interfaces, classes, and strict typing. This leads to better maintainability and fewer bugs.

  3. Enhanced Developer Productivity:
    TypeScript integrates seamlessly with popular code editors like Visual Studio Code, providing intelligent code completion, type checking, and refactoring tools. These features significantly enhance developer productivity.

  4. Scalability:
    TypeScript is particularly suited for large-scale projects. Its type system and modular structure make it easier to manage complex codebases.

  5. Compatibility with JavaScript:
    Since TypeScript is a superset of JavaScript, existing JavaScript code can be gradually migrated to TypeScript. This makes adoption smooth for projects with an existing JavaScript codebase.

  6. Strong Community and Ecosystem:
    TypeScript has a strong community and is widely adopted in the industry. Many modern frameworks, such as Angular, NestJS, and Deno, are built with TypeScript in mind.


TypeScript vs JavaScript

While JavaScript is a dynamic, interpreted language, TypeScript adds a static type system and compiles down to JavaScript. Here’s a comparison:

Feature JavaScript TypeScript
Typing Dynamic Static
Error Checking Runtime Compile-time
Object-Oriented Features Limited Full support (classes, interfaces, access modifiers)
Tooling Support Basic Excellent (VS Code, IntelliSense)
Code Scalability Moderate High
Adoption Universal Growing rapidly

TypeScript in Frameworks and Libraries

  1. Angular:
    Angular, a popular front-end framework, is built entirely with TypeScript. Using TypeScript in Angular projects enhances type safety and enables better tooling and code completion.

  2. React:
    While React is primarily JavaScript-based, using TypeScript with React provides benefits like prop type validation and more predictable component behavior.

    type Props = { name: string; age: number };
    const Person: React.FC<Props> = ({ name, age }) => (
        <div>{name} is {age} years old</div>
    );
    
  3. Node.js:
    TypeScript can also be used in backend development with Node.js. Using TypeScript in Node projects provides better type safety and reduces runtime errors in server-side code.

  4. Vue.js:
    Vue 3 supports TypeScript natively, allowing developers to write strongly typed components for better maintainability.


TypeScript Compiler and Configuration

TypeScript requires a compiler (tsc) to convert .ts files into JavaScript. The compilation process can be customized using a tsconfig.json file, which specifies compiler options, file inclusion/exclusion, module systems, and more.

Example tsconfig.json:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "strict": true,
    "outDir": "./dist",
    "esModuleInterop": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

Key compiler options:

  • target: Specifies the JavaScript version for output (ES5, ES6, etc.).

  • module: Defines the module system (CommonJS, ESNext, etc.).

  • strict: Enables all strict type-checking options.

  • outDir: Directory where compiled JavaScript files are stored.

 

Fresher Interview Questions

 

1. What is TypeScript?

Answer:
TypeScript is an open-source programming language developed by Microsoft. It is a superset of JavaScript, which means every valid JavaScript code is also valid TypeScript code. TypeScript adds static typing and object-oriented features to JavaScript, making it easier to write large-scale applications.

Key features:

  • Optional static typing

  • Type inference

  • Interfaces and classes

  • Enums

  • Generics

  • Advanced tooling support


2. Difference between TypeScript and JavaScript

Feature JavaScript TypeScript
Type Checking Dynamic Static (optional)
Compilation Not required Requires compilation to JS
Support for OOP Limited (ES6 classes) Full support (interfaces, classes, access modifiers)
IDE Support Basic Advanced (IntelliSense, autocomplete)
Error Detection Runtime Compile-time

3. What are the advantages of using TypeScript?

Answer:

  1. Type Safety: Helps catch errors at compile-time rather than runtime.

  2. Improved IDE Support: Provides IntelliSense, auto-completion, and better refactoring support.

  3. Scalability: Suitable for large projects because of classes, interfaces, and modules.

  4. Code Maintainability: Easier to understand and maintain code.

  5. Cross-Platform: Compiles to plain JavaScript, compatible with all browsers.


4. What is a Type in TypeScript?

Answer:
A type defines the shape and behavior of data. TypeScript provides built-in types such as:

  • number

  • string

  • boolean

  • any

  • void

  • null / undefined

  • never

Example:

let age: number = 25;
let name: string = "Yash";
let isActive: boolean = true;
let data: any = "Can be anything";

5. What is the any type?

Answer:
The any type allows a variable to hold any type of value. It disables type checking for that variable.

Example:

let value: any = 10;
value = "Hello"; // No error
value = true;    // Still no error

Note: Using any often defeats the purpose of TypeScript, so it should be used sparingly.


6. What are Interfaces in TypeScript?

Answer:
Interfaces define a contract for objects, specifying which properties or methods an object should have. They help in type-checking object structures.

Example:

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

let user: Person = {
    name: "Yash",
    age: 25,
    greet() {
        console.log("Hello!");
    }
};

7. What are Classes in TypeScript?

Answer:
TypeScript supports object-oriented programming. Classes can have properties, methods, constructors, and access modifiers (public, private, protected).

Example:

class Employee {
    private id: number;
    public name: string;

    constructor(id: number, name: string) {
        this.id = id;
        this.name = name;
    }

    display(): void {
        console.log(`Employee ID: ${this.id}, Name: ${this.name}`);
    }
}

let emp = new Employee(1, "Yash");
emp.display();

8. What is an Enum in TypeScript?

Answer:
Enums allow you to define a set of named constants.

Example:

enum Direction {
    Up = 1,
    Down,
    Left,
    Right
}

let move: Direction = Direction.Left;
console.log(move); // Output: 3

9. What is a Tuple in TypeScript?

Answer:
A tuple is an array with fixed types at each position.

Example:

let person: [string, number];
person = ["Yash", 25]; // Valid
// person = [25, "Yash"]; // Error

10. Difference between let, const, and var in TypeScript

Keyword Scope Reassignable Hoisting
var Function Yes Yes
let Block Yes No
const Block No No

11. What is a Union Type?

Answer:
Union types allow a variable to hold multiple types.

Example:

let value: string | number;
value = "Hello"; // Valid
value = 25;      // Valid
// value = true; // Error

12. What is Type Assertion?

Answer:
Type assertion tells the compiler to treat a variable as a specific type.

Syntax:

let someValue: any = "Hello World";
let strLength: number = (someValue as string).length;

13. What are Generics in TypeScript?

Answer:
Generics allow you to create reusable components that work with multiple types.

Example:

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

let output1 = identity<string>("Hello");
let output2 = identity<number>(100);

14. Difference between interface and type

Feature Interface Type Alias
Extension Can extend other interfaces Can use intersections (&)
Declaration Merge Yes No
Use Case Objects, class contracts Union, tuple, primitive types

15. How do you compile TypeScript code?

Answer:
TypeScript code is compiled into JavaScript using the TypeScript compiler (tsc).

Steps:

  1. Install TypeScript: npm install -g typescript

  2. Compile: tsc filename.ts → produces filename.js

  3. Run JS in browser or Node.js


16. Difference between undefined and null

  • undefined → variable declared but not assigned.

  • null → variable explicitly assigned "no value".

Example:

let a: number;
console.log(a); // undefined
let b: number | null = null;
console.log(b); // null

17. What is the never type?

Answer:
never represents a value that never occurs. It is used in functions that throw errors or run infinitely.

Example:

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

function infiniteLoop(): never {
    while(true) {}
}

18. How is TypeScript better for large projects?

  • Detects errors before runtime

  • Supports OOP concepts

  • Provides modular architecture with ES modules

  • Works well with modern frameworks like Angular, React, Node.js

  • Easier refactoring and code maintenance


19. What are Decorators in TypeScript?

Answer:
Decorators are annotations used to modify classes or methods. They are mostly used in Angular.

Example:

function log(target: any, key: string) {
    console.log(`${key} method called`);
}

class Calculator {
    @log
    add(a: number, b: number) {
        return a + b;
    }
}

20. What is the unknown type in TypeScript?

Answer:
The unknown type is similar to any, but it is safer because you cannot perform operations on it directly without type checking.

Example:

let value: unknown;
value = 10;
value = "Hello";

let str: string;
// str = value; // Error
if (typeof value === "string") {
    str = value; // OK after type check
}

21. What is the difference between any and unknown?

Feature any unknown
Assignment Can assign to any type Can’t assign without type check
Safety Unsafe Safe
Use Case Legacy code, dynamic data Safer alternative to any

22. What is a Module in TypeScript?

Answer:
Modules are files that export code (variables, functions, classes) so it can be imported in other files. They help organize code in large projects.

Example:
math.ts

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

app.ts

import { add } from "./math";
console.log(add(5, 10));

23. What is a Namespace in TypeScript?

Answer:
Namespaces group related code inside a single logical unit. They are mostly used in legacy TypeScript code for modularization.

Example:

namespace Utility {
    export function log(message: string) {
        console.log(message);
    }
}

Utility.log("Hello World!");

24. What is the difference between Module and Namespace?

Feature Module Namespace
Syntax export / import namespace keyword
Scope File-based Can be multiple in one file
Use Case Modern code, ES6 style Older TypeScript projects
Loading Supports lazy loading Always loaded

25. What are Access Modifiers in TypeScript?

Answer:
Access modifiers control visibility of class members:

  • public → accessible everywhere (default)

  • private → accessible only inside the class

  • protected → accessible in the class and its subclasses

Example:

class Person {
    public name: string;
    private age: number;
    protected gender: string;

    constructor(name: string, age: number, gender: string) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
}

26. What is a Constructor in TypeScript?

Answer:
A constructor is a special method used to initialize class properties.

Example:

class Employee {
    constructor(public id: number, public name: string) {}
}

let emp = new Employee(1, "Yash");
console.log(emp.name); // Output: Yash

27. What is Method Overloading in TypeScript?

Answer:
TypeScript supports method overloading by allowing multiple type signatures for the same method.

Example:

class Calculator {
    add(a: number, b: number): number;
    add(a: string, b: string): string;
    add(a: any, b: any): any {
        return a + b;
    }
}

let calc = new Calculator();
console.log(calc.add(5, 10));      // 15
console.log(calc.add("Hello ", "TS")); // Hello TS

28. What are Readonly properties in TypeScript?

Answer:
readonly makes class or interface properties immutable after initialization.

Example:

class Book {
    readonly title: string;

    constructor(title: string) {
        this.title = title;
    }
}

let book = new Book("TypeScript Guide");
// book.title = "New Title"; // Error

29. What are Optional Properties in TypeScript?

Answer:
Optional properties are declared using ? and may or may not be present in an object.

Example:

interface User {
    name: string;
    age?: number;
}

let user1: User = { name: "Yash" };
let user2: User = { name: "Amit", age: 25 };

30. What is the difference between interface and abstract class?

Feature Interface Abstract Class
Implementation Only declarations Can have implementations
Instantiation Cannot instantiate Cannot instantiate
Multiple Inheritance Supports multiple interfaces Single inheritance only
Use Case Contract for objects Base class with shared logic

31. How to create a ReadonlyArray in TypeScript?

Answer:
ReadonlyArray<T> prevents modification of the array elements.

Example:

let numbers: ReadonlyArray<number> = [1, 2, 3];
// numbers.push(4); // Error
// numbers[0] = 0;  // Error

32. What are Tuples with Optional and Rest Elements?

Answer:
TypeScript allows optional elements and rest elements in tuples.

Example:

let tuple1: [string, number?] = ["Yash"];
let tuple2: [number, ...string[]] = [1, "a", "b"];

33. What is a Literal Type in TypeScript?

Answer:
Literal types allow variables to hold only specific values.

Example:

let direction: "Up" | "Down" | "Left" | "Right";
direction = "Up";   // OK
// direction = "Forward"; // Error

34. What is the difference between interface and type for objects?

  • Both can define object shapes

  • interface supports declaration merging

  • type can define unions, intersections, primitives

  • In modern TypeScript, interfaces are preferred for object contracts


35. What are Conditional Types in TypeScript?

Answer:
Conditional types allow types to depend on other types.

Example:

type Check<T> = T extends string ? "Yes" : "No";
type A = Check<string>; // Yes
type B = Check<number>; // No

36. What is a Mapped Type in TypeScript?

Answer:
Mapped types allow you to create new types by transforming properties of an existing type.

Example:

type Person = { name: string; age: number };
type ReadonlyPerson = { readonly [K in keyof Person]: Person[K] };

37. What is keyof operator in TypeScript?

Answer:
keyof returns the keys of a type as a union.

Example:

type Person = { name: string; age: number };
type PersonKeys = keyof Person; // "name" | "age"

38. What is typeof type operator in TypeScript?

Answer:
typeof can be used to get the type of a variable or property.

Example:

let name = "Yash";
type NameType = typeof name; // string

39. How to make properties optional or nullable?

Answer:

  • Optional: Use ?

  • Nullable: Use | null

Example:

interface User {
    name: string;
    age?: number | null;
}

40. What is a Utility Type in TypeScript?

Answer:
Utility types are built-in generic types to transform or manipulate types. Examples:

  • Partial<T> → makes all properties optional

  • Required<T> → makes all properties required

  • Readonly<T> → makes all properties readonly

  • Pick<T, K> → picks some properties from T

  • Omit<T, K> → omits some properties from T

Example:

interface User {
    name: string;
    age: number;
}
type PartialUser = Partial<User>; // { name?: string; age?: number }

 

Experienced Interview Questions

 

1. What are Advanced Types in TypeScript?

Answer:
TypeScript provides advanced types to model complex scenarios:

  1. Union Types – variable can hold multiple types (string | number).

  2. Intersection Types – combine multiple types (type A = B & C).

  3. Literal Types – restrict a value to specific constants ("Up" | "Down").

  4. Mapped Types – transform types dynamically ({ [K in keyof T]: ... }).

  5. Conditional Types – type depends on another type (T extends U ? X : Y).

  6. Utility Types – built-in transformations (Partial<T>, Pick<T>).

  7. Index Types – access keys dynamically (keyof T, T[K]).

Example:

type Person = { name: string; age: number };
type ReadonlyPerson = { readonly [K in keyof Person]: Person[K] };

2. How do you manage large TypeScript projects?

Answer:

  1. Module-based architecture – split code into multiple files using import/export.

  2. Namespaces – rarely used now; modules are preferred.

  3. tsconfig.json – configure compiler options (strict, esModuleInterop, target).

  4. Linting – ESLint with TypeScript plugin for consistent code.

  5. Type safety – strict typing to prevent runtime errors.

  6. Interface & Type usage – define contracts for classes and objects.

  7. Generics – reusable and flexible components.

  8. Build tools – Webpack, Rollup, or Vite for bundling.


3. Explain TypeScript Generics and use cases

Answer:
Generics allow creating reusable components with type flexibility.

Example:

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

interface Response<T> {
    data: T;
    error: string | null;
}

const res: Response<number> = { data: 100, error: null };

Use cases:

  • API responses (Response<T>).

  • Utility functions (e.g., arrays, filters).

  • Reusable classes (e.g., Stack<T>).


4. What is Type Inference and when do you need explicit types?

Answer:

  • TypeScript automatically infers types based on assigned values.

  • Explicit types are needed when:

    • The variable is declared without initialization.

    • You want stricter contracts or public APIs.

    • You deal with any values from dynamic sources.

Example:

let name = "Yash"; // inferred as string
let id: number;     // explicit type

5. How do you implement Dependency Injection in TypeScript (Angular context)?

Answer:
Angular uses TypeScript decorators to manage dependency injection.

Example:

@Injectable({ providedIn: 'root' })
export class ApiService {
    constructor(private http: HttpClient) {}
}

@Component({...})
export class AppComponent {
    constructor(private api: ApiService) {}
}
  • TypeScript’s types and interfaces make DI type-safe.

  • Helps in testing, modular design, and reusability.


6. What is Declaration Merging in TypeScript?

Answer:
Declaration merging happens when two declarations with the same name combine into one.

Example:

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

const u: User = { name: "Yash", age: 25 }; // merged interface

Use case:

  • Extending libraries.

  • Adding custom properties to third-party types.


7. How do you handle any, unknown, and strict type safety in large apps?

Answer:

  • Avoid any unless necessary; prefer unknown + type narrowing.

  • Use type guards and assertions.

  • Enable strict in tsconfig.json for strict checks.

Example:

function process(value: unknown) {
    if (typeof value === 'string') {
        console.log(value.toUpperCase());
    }
}

8. What is the difference between interface and type in advanced scenarios?

Feature Interface Type Alias
Extending interface A extends B type A = B & C
Declaration Merging Supported Not supported
Use Case Objects, Classes Objects, Primitives, Unions
Recommended Public APIs, Contracts Complex types or unions

9. How do you implement Mixins in TypeScript?

Answer:
Mixins allow reusing code across classes.

Example:

class CanEat {
    eat() { console.log("Eating"); }
}
class CanWalk {
    walk() { console.log("Walking"); }
}

class Person {}
interface Person extends CanEat, CanWalk {}
applyMixins(Person, [CanEat, CanWalk]);

function applyMixins(derived: any, bases: any[]) {
    bases.forEach(base => {
        Object.getOwnPropertyNames(base.prototype).forEach(name => {
            derived.prototype[name] = base.prototype[name];
        });
    });
}

const p = new Person();
p.eat();
p.walk();

10. Explain Type Guards and Custom Type Guards

Answer:
Type guards narrow down a type to a specific type.

Built-in:

if (typeof value === 'string') { ... }

Custom Type Guard:

interface Fish { swim(): void; }
interface Bird { fly(): void; }

function isFish(pet: Fish | Bird): pet is Fish {
    return (pet as Fish).swim !== undefined;
}

let pet: Fish | Bird = ...;
if (isFish(pet)) pet.swim();

11. How do you handle asynchronous operations in TypeScript?

Answer:
TypeScript supports Promises, async/await, and typed responses:

async function fetchData(): Promise<string> {
    const response = await fetch("https://api.example.com/data");
    const data: string = await response.text();
    return data;
}
  • Use generic interfaces for typed API responses.

  • Helps avoid runtime type errors.


12. How do you configure TypeScript for Node.js projects?

Answer:

  • Use tsconfig.json with settings:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true
  }
}
  • Compile using tsc or use ts-node for execution.

  • Use type definitions (@types/node) for Node.js APIs.


13. How do you handle modules and tree-shaking?

  • Use ES6 modules (import/export) instead of CommonJS for better tree-shaking.

  • Avoid default exports for named exports to optimize bundling.

  • Example:

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

14. What are Decorators in TypeScript (Advanced usage)?

Answer:

  • Decorators modify classes, methods, or properties at runtime.

  • Often used in Angular, NestJS, and logging/tracing libraries.

Example (Method decorator):

function Log(target: any, key: string, descriptor: PropertyDescriptor) {
    const original = descriptor.value;
    descriptor.value = function (...args: any[]) {
        console.log(`Calling ${key} with args`, args);
        return original.apply(this, args);
    };
}

class Calculator {
    @Log
    add(a: number, b: number) { return a + b; }
}

new Calculator().add(2, 3);

15. What are Index Signatures and Dynamic Properties?

Answer:
Index signatures define types for dynamic object properties.

interface StringMap {
    [key: string]: string;
}

let dict: StringMap = { name: "Yash", city: "Delhi" };

16. How do you implement Advanced Generics (Constraints)?

Answer:

function merge<T extends object, U extends object>(obj1: T, obj2: U): T & U {
    return { ...obj1, ...obj2 };
}

const merged = merge({ name: "Yash" }, { age: 25 });
  • Constraints (extends object) ensure safe operations.


17. How do you handle TypeScript with React or Angular projects?

  • React: .tsx files, React.FC or React.FunctionComponent, props and state typing.

  • Angular: services, components, directives, strong DI with typed interfaces.

  • Always strictly type props, state, services, and observables.


18. How do you debug TypeScript efficiently?

  • Use source maps ("sourceMap": true) to debug TS in browser or Node.

  • Combine VSCode breakpoints with type hints.

  • Enable strict compiler options to catch errors early.

  • Use ts-node or nodemon for live debugging in Node.js.


19. How do you implement type-safe Redux/NgRx stores?

  • Use interfaces for state and typed actions.

  • Example (Redux):

interface AppState { count: number; }
const increment = (payload: number) => ({ type: 'INCREMENT', payload } as const);
  • Avoid any to leverage TypeScript’s type safety.


20. Best Practices for 4+ Years TypeScript Projects

  1. Enable strict and noImplicitAny in tsconfig.json.

  2. Use interfaces over type aliases for object contracts.

  3. Leverage Generics for reusable code.

  4. Avoid any; prefer unknown + type guards.

  5. Use decorators for cross-cutting concerns.

  6. Modularize with ES6 modules, avoid global namespace pollution.

  7. Enable linting and formatting (ESLint, Prettier).

  8. Keep tsconfig.json optimized for production (strict null checks, noUnusedLocals).


20. What is the unknown type in TypeScript?

Answer:
The unknown type is similar to any but safer. You cannot perform operations on a variable of type unknown without first checking its type.

Example:

let value: unknown;
value = 10;
value = "Hello";

let str: string;
// str = value; // Error
if (typeof value === "string") {
    str = value; // Works after type check
}

21. Difference between any and unknown

Feature any unknown
Assignment Can assign to any type Requires type check
Safety Unsafe Safe
Use Case Legacy code, dynamic data Safer alternative to any

22. What is a Module in TypeScript?

Answer:
Modules allow you to split code into multiple files. Each module can export variables, functions, or classes and import them in other files.

Example:
math.ts

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

app.ts

import { add } from "./math";
console.log(add(5, 10));

23. What is a Namespace in TypeScript?

Answer:
Namespaces group related code together. Unlike modules, they can exist in a single file or across multiple files.

Example:

namespace Utility {
    export function log(message: string) {
        console.log(message);
    }
}

Utility.log("Hello World!");

24. Difference between Module and Namespace

Feature Module Namespace
Syntax export / import namespace keyword
Scope File-based Can span multiple files
Use Case Modern ES6 projects Legacy TypeScript projects
Loading Supports lazy loading Always loaded

25. Access Modifiers in TypeScript

Answer:

  • public → accessible everywhere (default).

  • private → accessible only within the class.

  • protected → accessible within the class and subclasses.

Example:

class Person {
    public name: string;
    private age: number;
    protected gender: string;

    constructor(name: string, age: number, gender: string) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
}

26. Constructor in TypeScript

Answer:
A constructor is a special method used to initialize class properties.

Example:

class Employee {
    constructor(public id: number, public name: string) {}
}

let emp = new Employee(1, "Yash");
console.log(emp.name); // Yash

27. Method Overloading in TypeScript

Answer:
TypeScript allows multiple type signatures for a method.

Example:

class Calculator {
    add(a: number, b: number): number;
    add(a: string, b: string): string;
    add(a: any, b: any): any {
        return a + b;
    }
}

let calc = new Calculator();
console.log(calc.add(5, 10));      // 15
console.log(calc.add("Hello ", "TS")); // Hello TS

28. Readonly properties

Answer:
readonly properties cannot be modified after initialization.

Example:

class Book {
    readonly title: string;

    constructor(title: string) {
        this.title = title;
    }
}

let book = new Book("TypeScript Guide");
// book.title = "New Title"; // Error

29. Optional Properties

Answer:
Optional properties are declared with ? and may or may not be present.

Example:

interface User {
    name: string;
    age?: number;
}

let user1: User = { name: "Yash" };
let user2: User = { name: "Amit", age: 25 };

30. Difference between interface and abstract class

Feature Interface Abstract Class
Implementation Only declarations Can have implementations
Instantiation Cannot instantiate Cannot instantiate
Multiple Inheritance Supports multiple interfaces Single inheritance only
Use Case Contract for objects Base class with shared logic

31. ReadonlyArray

Answer:
ReadonlyArray<T> prevents modification of array elements.

let numbers: ReadonlyArray<number> = [1, 2, 3];
// numbers.push(4); // Error

32. Tuples with Optional and Rest Elements

Answer:

let tuple1: [string, number?] = ["Yash"];
let tuple2: [number, ...string[]] = [1, "a", "b"];

33. Literal Types

Answer:
Restrict a variable to specific values.

let direction: "Up" | "Down" | "Left" | "Right";
direction = "Up";   // OK
// direction = "Forward"; // Error

34. Conditional Types

Answer:

type Check<T> = T extends string ? "Yes" : "No";
type A = Check<string>; // Yes
type B = Check<number>; // No

35. Mapped Types

Answer:

type Person = { name: string; age: number };
type ReadonlyPerson = { readonly [K in keyof Person]: Person[K] };

36. keyof operator

Answer:
Returns the keys of a type as a union.

type Person = { name: string; age: number };
type PersonKeys = keyof Person; // "name" | "age"

37. typeof type operator

Answer:

let name = "Yash";
type NameType = typeof name; // string

38. Optional and Nullable Properties

Answer:

interface User {
    name: string;
    age?: number | null;
}

39. Utility Types

  • Partial<T> → all properties optional

  • Required<T> → all properties required

  • Readonly<T> → all properties readonly

  • Pick<T,K> → picks selected properties

  • Omit<T,K> → omits selected properties

Example:

interface User { name: string; age: number }
type PartialUser = Partial<User>; // { name?: string; age?: number }

40. Type Assertions

Answer:
Tell the compiler a variable is of a specific type.

let someValue: any = "Hello World";
let strLength: number = (someValue as string).length;