Interview Questions

Get ready for your next interview with our comprehensive question library

TypeScript Interview Questions

Filter by Difficulty

1.

What are the main benefits of using TypeScript over JavaScript?

beginner
  • Early error detection: Catches type-related errors at compile time
  • Better developer experience: Enhanced IntelliSense and autocomplete
  • Improved maintainability: Self-documenting code through type annotations
  • Refactoring confidence: Safe refactoring with type checking
  • Team collaboration: Clear contracts between different parts of the codebase
  • Modern JavaScript features: Access to latest ES features with backward compatibility
2.

How do you compile TypeScript code?

beginner

TypeScript code is compiled using the TypeScript compiler (tsc):

# Install TypeScript globally
npm install -g typescript

# Compile a single file
tsc app.ts

# Compile with watch mode
tsc app.ts --watch

# Compile using tsconfig.json
tsc

The compiler reads .ts files and outputs .js files that can run in any JavaScript environment.

3.

What is type inference in TypeScript?

beginner

Type inference is TypeScript's ability to automatically determine types without explicit type annotations. The compiler analyzes the code and infers the most appropriate types.

let message = "Hello"; // TypeScript infers string type
let count = 42; // TypeScript infers number type
let isActive = true; // TypeScript infers boolean type

function add(a: number, b: number) {
  return a + b; // Return type inferred as number
}
4.

What are type annotations and how do you use them?

beginner

Type annotations are explicit type declarations that tell TypeScript what type a variable, parameter, or return value should be.

// Variable annotations
let username: string = "john";
let age: number = 25;
let isLoggedIn: boolean = false;

// Function parameter and return type annotations
function greet(name: string): string {
  return `Hello, ${name}!`;
}

// Array annotations
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["Alice", "Bob"];
5.

What are the primitive types in TypeScript?

beginner

TypeScript supports all JavaScript primitive types plus additional ones:

  • string: Text data
  • number: Numeric values (integers and floats)
  • boolean: True/false values
  • null: Intentional absence of value
  • undefined: Uninitialized value
  • symbol: Unique identifiers
  • bigint: Large integers
  • void: Absence of return value
  • never: Values that never occur
  • any: Disables type checking
  • unknown: Type-safe alternative to any
6.

What is an interface in TypeScript?

beginner

An interface defines the structure of an object, specifying what properties and methods it should have.

interface User {
  id: number;
  name: string;
  email: string;
  isActive?: boolean; // Optional property
  readonly createdAt: Date; // Read-only property
}

const user: User = {
  id: 1,
  name: "John Doe",
  email: "john@example.com",
  createdAt: new Date()
};
7.

How do you extend interfaces in TypeScript?

beginner

Use the extends keyword to inherit properties from other interfaces:

interface Shape {
  color: string;
}

interface Circle extends Shape {
  radius: number;
}

interface Rectangle extends Shape {
  width: number;
  height: number;
}

// Multiple inheritance
interface TimestampedShape extends Shape, Timestamped {
  area: number;
}

interface Timestamped {
  createdAt: Date;
  updatedAt: Date;
}
8.

What are optional properties and how do you define them?

beginner

Optional properties are marked with ? and may or may not be present in the object:

interface Config {
  apiUrl: string;
  timeout?: number; // Optional
  retries?: number; // Optional
  debug?: boolean; // Optional
}

const config: Config = {
  apiUrl: "https://api.example.com"
  // Other properties can be omitted
};

// Function with optional parameters
function createUser(name: string, age?: number): User {
  return {
    name,
    age: age ?? 18 // Default value if not provided
  };
}
9.

What are readonly properties in TypeScript?

beginner

Readonly properties can only be assigned during initialization and cannot be modified afterward:

interface Point {
  readonly x: number;
  readonly y: number;
}

const point: Point = { x: 10, y: 20 };
// point.x = 30; // Error: Cannot assign to 'x' because it is read-only

// Readonly arrays
const readonlyArray: readonly number[] = [1, 2, 3];
// readonlyArray.push(4); // Error: Property 'push' does not exist

// ReadonlyArray type
const numbers: ReadonlyArray<number> = [1, 2, 3];
10.

How do you define a class in TypeScript?

beginner

Classes in TypeScript include type annotations and access modifiers:

class Person {
  // Properties
  private _id: number;
  protected name: string;
  public email: string;

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

  // Methods
  public greet(): string {
    return `Hello, I'm ${this.name}`;
  }

  protected getId(): number {
    return this._id;
  }
}
11.

What are access modifiers in TypeScript?

beginner

TypeScript provides three access modifiers:

  • public (default): Accessible everywhere
  • private: Accessible only within the same class
  • protected: Accessible within the class and its subclasses
class BankAccount {
  public accountNumber: string;
  private balance: number;
  protected accountType: string;

  constructor(accountNumber: string, initialBalance: number) {
    this.accountNumber = accountNumber;
    this.balance = initialBalance;
    this.accountType = "savings";
  }

  public getBalance(): number {
    return this.balance; // Accessing private property within class
  }

  private calculateInterest(): number {
    return this.balance * 0.05;
  }
}

class PremiumAccount extends BankAccount {
  constructor(accountNumber: string, initialBalance: number) {
    super(accountNumber, initialBalance);
    // this.balance; // Error: private property
    console.log(this.accountType); // OK: protected property
  }
}
12.

How do ES6 modules work in TypeScript?

beginner

TypeScript fully supports ES6 module syntax for importing and exporting:

// math.ts
export function add(a: number, b: number): number {
  return a + b;
}

export function subtract(a: number, b: number): number {
  return a - b;
}

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

export const PI = 3.14159;

// app.ts
import multiply, { add, subtract, PI } from './math';
import * as MathUtils from './math';

console.log(add(5, 3)); // 8
console.log(multiply(4, 2)); // 8
console.log(MathUtils.PI); // 3.14159
13.

What is `NonNullable<T>` utility type?

beginner

NonNullable<T> removes null and undefined from a type:

type MaybeString = string | null | undefined;
type DefinitelyString = NonNullable<MaybeString>; // string

function processValue(value: string | null | undefined): void {
  if (value !== null && value !== undefined) {
    // Type narrowing
    const processed: NonNullable<typeof value> = value; // string
    console.log(processed.toUpperCase());
  }
}

// Useful with arrays
type ArrayItem<T> = T extends (infer U)[] ? NonNullable<U> : never;
type StringArrayItem = ArrayItem<(string | null)[]>; // string
14.

How do you handle errors in TypeScript?

beginner

TypeScript supports JavaScript's error handling mechanisms with additional type safety:

// Basic try-catch
function parseNumber(value: string): number {
  try {
    const parsed = parseInt(value);
    if (isNaN(parsed)) {
      throw new Error(`Invalid number: ${value}`);
    }
    return parsed;
  } catch (error) {
    if (error instanceof Error) {
      console.error(error.message);
    }
    throw error;
  }
}

// Custom error types
class ValidationError extends Error {
  constructor(
    message: string,
    public field: string,
    public value: any
  ) {
    super(message);
    this.name = 'ValidationError';
  }
}

function validateEmail(email: string): void {
  if (!email.includes('@')) {
    throw new ValidationError('Invalid email format', 'email', email);
  }
}
15.

How do you stay updated with TypeScript evolution?

beginner

Upgrade to Premium to see the answer

Upgrade to Premium
16.

What advice would you give to someone learning TypeScript?

beginner

Upgrade to Premium to see the answer

Upgrade to Premium
17.

What are your thoughts on TypeScript's future and ecosystem?

beginner

Upgrade to Premium to see the answer

Upgrade to Premium
18.

What is the difference between `any` and `unknown` types?

intermediate

Upgrade to Premium to see the answer

Upgrade to Premium
19.

Explain union types and intersection types

intermediate

Upgrade to Premium to see the answer

Upgrade to Premium
20.

What are literal types in TypeScript?

intermediate

Upgrade to Premium to see the answer

Upgrade to Premium
Showing 1 to 20 of 99 results

Premium Plan

$10.00 /monthly
  • Access all premium content - interview questions, and other learning resources

  • We regularly update our features and content, to ensure you get the most relevant and updated premium content.

  • 1000 monthly credits

  • Cancel anytime