TechSchool
Home / Interview questions / TypeScript

TypeScript interview questions

46 questions about TypeScript with short answers and code. Each answer links to a full lesson on this site. Free, with no signup and no ads.

Basics

1. What is TypeScript?

TypeScript is an open-source language from Microsoft. It is a superset of JavaScript that adds an optional static type system. TypeScript code compiles to plain JavaScript.

Full lesson: Ts intro

2. How do you install TypeScript?

You install TypeScript with the npm tool. The global install command makes the tsc command available. Then you can check the version.

npm install -g typescript
tsc -v

Full lesson: Ts install

3. How do you compile a TypeScript file?

You compile a TypeScript file with the tsc command. The compiler writes a JavaScript file with the same name. Then you run the JavaScript file with node.

tsc Example.ts
node Example.js

Full lesson: Ts basic syntax

4. What are the basic types in TypeScript?

TypeScript has string, number, boolean, array, tuple, enum, and any types. Each type tells the compiler the shape of the data. A type annotation comes after the variable name.

let name: string = "Alice";
let age: number = 30;
let isDone: boolean = true;

Full lesson: Ts type

5. How do you declare a variable with a type in TypeScript?

You write the variable name, a colon, and the type. You can use let, const, or var. The const keyword stops reassignment.

let count: number = 5;
const city: string = "Paris";

Full lesson: Ts variables

6. How do you declare an array in TypeScript?

You add square brackets after the element type. You can also use the Array generic form. The array holds values of one type.

let sites: string[] = ["Google", "Example"];
let nums: Array<number> = [1, 2, 3];

Full lesson: Ts array

7. How do you define a function with typed parameters?

You put a type after each parameter name. You also put a type after the parameter list for the return value. The compiler then checks each call.

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

Full lesson: Ts function

8. How do you write an if statement in TypeScript?

You write the if keyword and a condition in parentheses. The code block runs when the condition is true. You can add else for the other case.

let score: number = 80;
if (score >= 60) {
  console.log("Pass");
}

Full lesson: Ts if statement

9. How do you write a for loop in TypeScript?

A for loop has three parts in parentheses. The parts are the start, the condition, and the step. The loop repeats the block while the condition is true.

for (let i = 0; i < 3; i++) {
  console.log(i);
}

Full lesson: Ts loop

10. How do you define a class in TypeScript?

You use the class keyword and a class name. The class holds fields, a constructor, and methods. You create an object with the new keyword.

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

Full lesson: Ts class

11. How does class inheritance work in TypeScript?

A subclass uses the extends keyword to inherit from a parent class. The subclass calls super() to run the parent constructor. The subclass can override parent methods.

class Animal {
  speak(): void { console.log("sound"); }
}
class Dog extends Animal {
  speak(): void { console.log("woof"); }
}

Full lesson: Ts class inheritance

12. How do you define an interface in TypeScript?

You use the interface keyword and a name. The body lists the property names and their types. An object that matches the shape can use the interface as its type.

interface User {
  id: number;
  name: string;
}
let u: User = { id: 1, name: "Alice" };

Full lesson: Ts interface

13. How do you export and import a module in TypeScript?

You add the export keyword to a value in one file. Another file uses the import keyword and a path. Named exports use curly braces in the import.

// user.ts
export const name = "Alice";
// main.ts
import { name } from "./user";

Full lesson: Ts module

14. Why does a string literal fail when you assign it to a number variable?

The compiler checks the type of each value. A string value does not match a number type. The fix is to change the value or the type annotation.

let age: number = 30;
age = "thirty"; // Error

Full lesson: Ts type

15. Why does an object literal fail when it has an extra property?

TypeScript rejects extra properties in a direct object literal. The object must match the interface exactly. The fix is to remove the extra property or add it to the interface.

interface User { id: number; }
let u: User = { id: 1, age: 30 }; // Error

Full lesson: Ts interface

Intermediate

16. Why does the compiler reject this.name in a class method?

The this keyword loses its class meaning inside a plain callback function. The callback runs with a different this value. The fix is to use an arrow function.

class Counter {
  count = 0;
  start(): void {
    setTimeout(() => { this.count++; }, 100);
  }
}

Full lesson: Ts class

17. How do you create an object with keys and values in TypeScript?

You write a set of key-value pairs inside curly braces. The values can be strings, numbers, functions, or arrays. You then read a value with dot notation.

var sites = { site1: "Example", site2: "Google" };
console.log(sites.site1);

Full lesson: Ts object

18. How do you create a string in TypeScript?

You can use a string literal or the String constructor. A string literal creates the primitive string type. The literal form is the common and fast way.

const txt1: string = "Hello";
var txt2 = new String("string");

Full lesson: Ts string

19. How do you define a type alias in TypeScript?

You use the type keyword and give a name to an existing type. A type alias makes complex types shorter and easier to read. You can also give an alias to a union type.

type ID = string | number;
var uid: ID = 123;

Full lesson: Ts type alias

20. How do you use a literal type to limit allowed values?

You set the type to a list of exact values. The variable can hold only one value from the list. A wrong value causes a compile error.

var direction: "up" | "down" = "up";
// direction = "upup"; // Error

Full lesson: Ts literal types

21. What is the difference between any and unknown?

The any type skips all type checks. The unknown type is a safe any and needs a check before use. Use unknown when the type is not clear yet.

let a: any = 1;
let u: unknown = "text";
if (typeof u === "string") { console.log(u.length); }

Full lesson: Ts special types

22. What does the void type mean in a function?

The void type means the function returns no value. You use it as the return type of such a function. The function can still return undefined.

function logMsg(msg: string): void {
  console.log(msg);
}

Full lesson: Ts special types

23. What does the never type mean?

The never type means a value that never occurs. A function that always throws has the return type never. The never type is a subtype of all types.

function fail(msg: string): never {
  throw new Error(msg);
}

Full lesson: Ts special types

24. How do you narrow a union type with a type guard?

You check the runtime type with a condition such as typeof. The compiler then knows the exact type inside that block. This lets you use type-specific properties in safety.

function len(x: string | number) {
  if (typeof x === "string") { return x.length; }
  return x;
}

Full lesson: Ts type guards

25. How do you make all properties of a type optional?

You use the built-in Partial utility type. Partial adds the optional modifier to every property. You can then pass an object with only some keys.

interface User { id: number; name: string; }
type PartUser = Partial<User>;
const u: PartUser = { name: "Alice" };

Full lesson: Ts utility types

26. How do you pick only some properties from a type?

You use the Pick utility type with the keys you want. Pick builds a new type from those keys only. The Omit type does the opposite and removes keys.

interface User { id: number; name: string; email: string; }
type NameOnly = Pick<User, "name">;

Full lesson: Ts utility types

27. How do you write a mapped type that adds the readonly modifier?

You write a type that loops over the keys of another type. The in keyof syntax visits each property. You add readonly before the property name.

type ReadOnly<T> = { readonly [P in keyof T]: T[P] };
interface User { id: number; }
type RUser = ReadOnly<User>;

Full lesson: Ts mapped types

28. Why does a function that must return a value fail to compile?

The function declares a return type but a code path returns nothing. The compiler checks every path against the return type. Add a return statement to each path.

function getNum(): number {
  // missing return
}
// Error: lacks ending return statement

Full lesson: Ts function

29. Why does this code fail when you call a method on a possibly undefined value?

The variable type includes undefined. The compiler blocks a method call on a value that can be undefined. Check the value first or use optional chaining.

let name: string | undefined;
// name.length; // Error
console.log(name?.length);

Full lesson: Ts type guards

30. Why does the compiler reject a class that does not implement all interface members?

A class that implements an interface must define every property and method. A missing member breaks the contract. Add the missing member or remove the implements clause.

interface IPerson { firstName: string; sayHi: () => string; }
class Person implements IPerson {
  firstName = "Ann";
  // sayHi is missing
}

Full lesson: Ts interface

Common mistakes

31. Why does an object with a function value fail when the type expects a method signature?

The object type must match the declared interface exactly. A function property must have the same signature as the interface method. Fix the parameter list or the return type.

interface IPerson { sayHi: () => string; }
const c: IPerson = {
  sayHi: () => "Hi"
};

Full lesson: Ts interface

32. What is the basic structure of a TypeScript program?

A TypeScript program has three parts. It has statements, variables, and functions. The compiler runs the program from top to bottom.

let message: string = "Hello";
console.log(message);

Full lesson: Typescript basic structure

33. How do you use a loop to repeat a block of code in TypeScript?

Use a for loop to repeat a block a fixed number of times. Use a while loop to repeat while a condition is true.

for (let i = 0; i < 3; i++) {
  console.log(i);
}

Full lesson: Ts loop

34. How do you define a function that returns a value in TypeScript?

Add a return type after the parameter list. The function must return a value of that type.

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

Full lesson: Ts function

35. How do you use an object type in TypeScript?

An object type lists property names and their types. You can assign an object that matches the type.

let user: { name: string; age: number } = {
  name: "Alice",
  age: 30
};

Full lesson: Ts object

36. How do you use a type alias for an object type?

A type alias gives a name to a type. You can reuse the name in many places.

type Point = { x: number; y: number };
let p: Point = { x: 1, y: 2 };

Full lesson: Ts type alias

37. How do you use a literal type in a union?

A literal type allows only a specific value. A union of literal types allows only those values.

let direction: "up" | "down" = "up";
direction = "left"; // Error

Full lesson: Ts literal types

38. How do you use a mapped type to make all properties readonly?

A mapped type creates a new type from an old type. Add the readonly modifier in the mapping syntax.

type ReadonlyUser = {
  readonly [P in keyof User]: User[P]
};

Full lesson: Ts mapped types

39. How do you use the Partial utility type?

Partial<T> makes all properties of T optional. You can then create an object with only some properties.

interface User { id: number; name: string; }
type PartialUser = Partial<User>;
let u: PartialUser = { name: "Alice" };

Full lesson: Ts utility types

40. How do you use the Omit utility type?

Omit<T, K> creates a type without the properties K. You can then create an object without those properties.

interface User { id: number; name: string; email: string; }
type NoEmail = Omit<User, "email">;
let u: NoEmail = { id: 1, name: "Alice" };

Full lesson: Ts utility types

41. How do you use a type guard to check for a string?

Use the typeof operator in a condition. TypeScript then narrows the type inside the block.

function print(value: string | number) {
  if (typeof value === "string") {
    console.log(value.toUpperCase());
  }
}

Full lesson: Ts type guards

42. Why does a mapped type with a missing modifier fail to compile?

A mapped type must use the correct syntax. A missing modifier or a wrong key type causes an error.

type Bad = { [P in keyof User]?: User[P] }; // correct
type Wrong = { [P in User]?: User[P] }; // Error

Full lesson: Ts mapped types

43. Why does a literal type assignment fail when the value is not in the union?

A literal type allows only the listed values. Any other value causes a compile error.

let status: "active" | "inactive" = "active";
status = "pending"; // Error

Full lesson: Ts literal types

44. Why does a function with a void return type fail when it returns a value?

A void return type means the function returns no value. Returning a value causes a compile error.

function log(): void {
  return 1; // Error
}

Full lesson: Ts special types

45. Why does a never type assignment fail when you assign it to a number?

The never type has no values. You cannot assign a never value to a number variable.

let n: never;
let x: number = n; // Error

Full lesson: Ts special types

46. Why does a utility type fail when you use a wrong type argument?

A utility type expects a type that has the needed properties. A wrong type argument causes a compile error.

type Bad = Partial<number>; // Error

Full lesson: Ts utility types

More on TechSchool
See the TypeScript cheat sheet Python JavaScript HTML CSS React Vue 3 Node.js Java PHP C C++ C# Go SQL MongoDB Redis Linux Git Docker Data Structures