120+ Most Asked Typescript Interview Questions for All Levels

Facing a coding interview for a front end or full stack role, you may freeze when an interviewer asks about TypeScript types, generics, or type guards. Where do you start? This collection of TypeScript Interview Questions covers basics like types, interfaces, and enums as well as advanced topics such as conditional types, mapped types, utility types, decorators, async patterns, and compiler options, with clear examples and quick tips. To confidently crack their TypeScript interview by practicing 120+ of the most asked questions across all experience levels.

To help with that, Interview Coder's AI Interview Assistant offers guided practice, instant feedback, and tailored question sets so you can sharpen skills, track progress, and go into interviews with calm and focus.

Top 65 Typescript Interview Questions for Freshers

Blog image

1. Question: What are the primitive types in TypeScript?

Why you Might Get Asked This

Interviewers check whether you understand the basic building blocks of type systems and how TypeScript maps to JavaScript runtime values. This reveals if you can reason about data, function signatures, and simple type errors.

How to Answer

  • List the core primitives and map them to common JavaScript values.
  • Mention that TypeScript adds other special types (null, undefined, any, void, never, unknown) and how they relate.
  • Give short examples for string, number, and boolean.

Example Answer

string: "hello", number: 42, boolean: true. Example: let name: string = "Alice"; let age: number = 30; let active: boolean = false;

2. Question: Explain how the arrays work in TypeScript

Why you Might Get Asked This

Arrays are everywhere; the interviewer wants to see if you can type collections, prevent mixed-type errors, and choose between shorthand and generic syntax. This checks practical use of types and type inference.

How to Answer

  • Show the two common syntaxes: T[] and Array<T>.
  • Explain indexing starts at 0 and TypeScript enforces element types.
  • Give a short init and assignment example.

Example Answer

let values: number[] = [15, 20, 25]; OR let values: Array<number> = [15, 20, 25]; values[0] = 10;

3. Question: What is any type, and when to use it?

Why you Might Get Asked This

Hiring managers want to see whether you balance type safety with pragmatism and when you accept a loss of typing. This measures judgment about unknown runtime inputs and legacy code.

How to Answer

  • Define any as the escape hatch that disables type checking for that value.
  • Mention common use cases: third-party JSON, quick migration, or prototyping.
  • Warn about losing compiler guarantees and suggest alternatives like unknown or explicit interfaces.

Example Answer

const employee: any = JSON.parse(employeeData); console.log(employee.name); // allowed but not type-safe

4. Question: What is void, and when to use the void type?

Why you Might Get Asked This

The question tests if you can mark intent for functions that do not return useful values and handle callbacks correctly. It checks understanding of return types.

How to Answer

  • Explain void describes absence of a meaningful return value.
  • Use it on functions that only have side effects.
  • Note variables typed void can only hold undefined or null (depending on strictNullChecks).

Example Answer

function notify(): void { console.log("Notified"); }

5. Question: What is an unknown type, and when to use it in TypeScript?

Why you Might Get Asked This

Interviewers want to see if you prefer type-safe patterns over any and if you know how to narrow types before use. This shows you can handle external inputs safely.

How to Answer

  • Define unknown as a safer alternative to any; you must narrow or assert before using it.
  • Show narrowing via typeof, in checks, or user-defined type guards.
  • Give an example showing a compile error and the corrected narrowing/assertion.

Example Answer

let foo: unknown = "Akshay"; // let bar: string = foo; // error let bar: string = foo as string;

6. Question: What are the different keywords to declare variables in TypeScript?

Why you Might Get Asked This

This verifies you understand scope, mutability, and best practices for variable declarations in modern code. It also links to runtime JavaScript behavior.

How to Answer

  • Explain var is function-scoped and hoisted; avoid it in modern code.
  • Describe let as block-scoped and mutable.
  • Describe const as block-scoped and immutable reference to a value.

Example Answer

let a = 5; const b = 10; var c = "legacy"; // prefer let/const

7. Header: Arrow functions made simple

Question

Explain the arrow function syntax in TypeScript.

Why you Might Get Asked This

Arrow functions are common in modern code and callbacks; the interviewer wants to confirm you can annotate parameter and return types and know implicit returns and lexical this behavior.

How to Answer

  • Show basic arrow syntax with typed parameters and return type.
  • Mention single-expression implicit return.
  • Give an example used as a callback.

Example Answer

let add = (x: number, y: number): number => x + y; let fiveMultiples = numbers.filter(num => num % 5 === 0);

8. Header: Typing function signatures

Question: Provide the Syntax of a Function with the Type Annotations.

  • Why you might get asked this: Functions carry most program behavior; interviewers check you can declare argument types and return types to prevent runtime errors and document intent.

How to Answer

  • Show parameter type annotations and return type after ):.
  • Provide a short working example and a call.

Example Answer

function greet(name: string): string { return `Hello, ${name}`; } const greeting = greet("Anders");

9. Header: Creating typed object literals

Question

How to create objects in TypeScript?

Why you Might Get Asked This

Objects model real data. The interviewer wants to see if you can define shapes and enforce property types, a base skill for interfaces and classes.

How to Answer

  • Show inline object type annotations with property names and types.
  • Give an initialization example matching the shape.

Example Answer

let pt: { x: number; y: number } = { x: 10, y: 20 };

10. Header: Optional properties with ?

Question

How to specify optional properties in TypeScript?

Why you Might Get Asked This

Optional properties are common in APIs and partial updates; interviewers want to know you can model optional fields without disabling type checks.

How to Answer

  • Show the ? syntax after the property name.
  • Explain the compiler will accept objects missing that property.
  • Provide an example and late assignment.

Example Answer

let pt: { x: number; y: number; z?: number } = { x: 10, y: 20 }; pt.z = 30;

11. Header: Null handling basics

Question

Explain the concept of null and its use in TypeScript.

Why you Might Get Asked This

Handling missing values safely is critical. This checks your knowledge of nullable types and how to guard before accessing properties.

How to Answer

  • Define null as explicit absence of a value.
  • Show a union type allowing null and how to guard with a conditional.
  • Provide a short example using string | null and a runtime check.

Example Answer

function greet(name: string | null) { if (name === null) console.log("Name not provided"); else console.log(name.toUpperCase()); }

12. Header: Understanding undefined

Question

What is undefined in TypeScript?

Why you Might Get Asked This

Distinguishing undefined from null and knowing when values are uninitialized prevents runtime surprises. The question tests attention to JS semantics and strictNullChecks.

How to Answer

  • Define undefined as the default value for declared but uninitialized variables.
  • Contrast with null and show equality behavior.
  • Mention compiler options (strictNullChecks) affect handling.

Example Answer

let x: number | undefined; console.log(x); // undefined

13. Header: never for impossible returns

Question

Explain the purpose of the never type in TypeScript.

Why you Might Get Asked This

Never documents functions that cannot complete normally. Interviewers expect awareness of exhaustive checks and functions that throw or loop forever.

How to Answer

  • Define never as the type with no possible values.
  • Use it for functions that always throw or never return (infinite loops).
  • Give examples for throw and while(true).

Example Answer

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

14. Header: Enums for named constants

Question:

Explain how enums work in TypeScript?

Why you Might Get Asked This

Enums show you can create readable named constants and choose between numeric and string enums for clarity. This checks API design sense.

How to Answer

  • Show a basic numeric enum and default indexing.
  • Show how to set explicit numeric values and also string enums.
  • Provide a short usage example.

Example Answer

enum Team { Alpha, Beta, Gamma, Delta } let t: Team = Team.Delta; enum Author { Anders = "Anders", Hejlsberg = "Hejlsberg" }

15. Header: typeof as operator and type query

Question

What is the typeof operator? How is it used in TypeScript?

Why you Might Get Asked This

Typeof is used both at runtime and in type contexts to capture types from values. Interviewers test whether you can reuse types and narrow dynamically.

How to Answer

  • Explain runtime typeof returns a string like "number", "string".
  • Explain type query typeof T to refer to a variable or property type.
  • Give one runtime example and one type-level example.

Example Answer

console.log(typeof 10); // "number" let greeting = "hello"; type T = typeof greeting; // T is string

16. Header: Rest parameters and spread usage

Question

What are the rest parameters and arguments in TypeScript?

Why you Might Get Asked This

Variadic functions and spreading arrays are common patterns. This checks typing for flexible APIs and correct array typing for rest parameters.

How to Answer

  • Define rest parameters in function signature using ... and typed as T[].
  • Show using spread to pass array elements into calls or push arrays together.
  • Provide examples for both.

Example Answer

function add(...values: number[]) { return values.reduce((s, v) => s + v, 0); } const first = [1,2]; first.push(...[3,4]);

17. Header: Parameter destructuring with types

Question:

What is parameter destructuring?

Why you Might Get Asked This

Destructuring improves readability for functions that take config objects. Interviewers want to see safe typing when unpacking properties.

How to Answer

  • Show destructuring in the parameter list with an inline type or named type/interface.
  • Mention benefit: named parameters and clearer defaults.
  • Provide a short example using a type alias.

Example Answer

type ABC = { a: number; b: number; c: number }; function multiply({ a, b, c }: ABC) { console.log(a * b * c); }

18. Header: Class syntax essentials

Question

Explain the TypeScript class syntax.

Why you Might Get Asked This

Classes and OOP are in many codebases. Interviewers check constructor typing, member declarations, and method signatures.

How to Answer

  • Show property declarations with types and a typed constructor.
  • Include a method with a return type.
  • Give example of instantiation and method call.

Example Answer

class Employee { name: string; salary: number; constructor(name: string, salary: number) { this.name = name; this.salary = salary; } promote(): void { this.salary += 10000; } } let john = new Employee("John", 60000);

19. Header: Optional function parameters

Question

Provide the syntax for optional parameters in TypeScript.

Why you Might Get Asked This

Optional parameters affect call sites and overloads. This tests your understanding of function signatures and defaults.

How to Answer

  • Add ? after the parameter name to mark it optional.
  • Note optional parameters must come after required ones.
  • Show a default fallback inside the function or via default parameter.

Example Answer

function greet(name: string, greeting?: string) { if (!greeting) greeting = "Hello"; console.log(`${greeting}, ${name}`); }

20. Header: tsconfig.json role

Question

What is the purpose of the tsconfig.json file?

Why you Might Get Asked This

A tsconfig defines project scope and compiler options.

Interviewers want to confirm you can configure the compiler and control code generation.

How to Answer

  • Explain it marks a TypeScript project root and sets compilerOptions.
  • Mention include/exclude and common options like noImplicitAny, target, and module.
  • Optionally show a minimal example snippet.

Example Answer

A tsconfig.json defines compilerOptions, include/exclude. Example: { "compilerOptions": { "noImplicitAny": true, "sourceMap": true }, "include": ["src/**/*"] }

21. Header: Built-in and custom data types

Question

Explain the data types available in TypeScript.

Why you Might Get Asked This

The interviewer checks breadth of type knowledge: primitives, special types, and user-defined types like interfaces and enums. This shows your modeling ability.

How to Answer

  • List built-in primitives: string, number, boolean, null, undefined, any, void, never, unknown.
  • List user-defined types: arrays, enums, classes, interfaces, type aliases, tuples.
  • Mention when to pick each briefly.

Example Answer

Primitives and special types as above; custom types via interface, type alias, class, enum, and arrays/tuples for collections.

22. Header: Variable declaration options

Question

In how many ways we can declare variables in TypeScript?

Why you Might Get Asked This

This confirms familiarity with scope semantics and modern JS practices. It reveals whether you’ll use safe declarations in code.

How to Answer

  • List var, let, const and describe scope (function vs block) and mutability.
  • Recommend let/const for most code and const for immutable bindings.

Example Answer

var (function-scoped), let (block-scoped, mutable), const (block-scoped, immutable reference).

23. Header: Explicit variable typing

Question

How you can declare a explicit variables in Typescript?

Why you Might Get Asked This

Shows you can annotate types to get early errors and improve code readability, important for collaboration and API contracts.

How to Answer

  • Show syntax: let name: Type = value.
  • Explain compiler will enforce that type for future assignments.
  • Give a short example and show an invalid assignment causing an error.

Example Answer

let company_name: string = "GeeksforGeeks"; company_name = "Cricket"; // company_name = 28; // error

24. Header: Typed functions in practice

Question

How to declare a function with typed annotation in TypeScript?

Why you Might Get Asked This

Clear function signatures reduce bugs and help the compiler validate calls. Interviewers look for correct parameter and return annotations.

How to Answer

  • Show parameters annotated with types and return type after ).
  • Provide an example that demonstrates argument type checking.

Example Answer

function annotatedFunc(name: string, age: number): string { return `My name is ${name} and my age is ${age}.`; }

25. Header: any revisited and examples

Question

Describe the "any" type in TypeScript.

Why you Might Get Asked This

They want to know when you accept unsafely typed data and how you mitigate it. This gauges tradeoffs in migrations and third-party data handling.

How to Answer

  • Define any as disabling type checking for that value.
  • Show use case: parsing third-party JSON, but recommend casting or defining interfaces when possible.
  • Give sample parsing example.

Example Answer

let student: any = JSON.parse(studentData); console.log(student.studentName);

26. Header: Why pick TypeScript

Question

What are the advantages of using TypeScript?

Why you Might Get Asked This

Employers check whether you appreciate type safety benefits, tooling, and maintainability TypeScript brings to complex codebases.

How to Answer

  • Mention static typing, early compile-time errors, improved editor tooling, and cross-platform JS output.
  • Note better refactoring and easier onboarding with explicit types.

Example Answer

TypeScript compiles to JavaScript, provides static types, catches many errors at compile time, and improves IDE autocomplete and refactorability.

27. Header: Tradeoffs to consider

Question

List some disadvantages of using TypeScript.

Why you Might Get Asked This

Interviewers value realistic assessment: every tool has costs; they want to know you can weigh build complexity and dependencies.

How to Answer

  • Note build step and added compilation time.
  • Mention need for declaration files for some third-party libraries and occasional mismatches in d.ts quality.
  • Cite learning curve and added config complexity.

Example Answer

TypeScript needs compilation, sometimes requires type defs for libraries, and may add tooling overhead during setup.

28. Header: Void refresher

Question

Explain the void type in TypeScript.

Why you Might Get Asked This

Confirms you know how to type functions with no meaningful return and understand variable assignment limits for void.

How to Answer

  • Define void as representing absence of a return value.
  • Show typical use on functions and note variables of type void can only take null/undefined (depending on config).
  • Provide a short example.

Example Answer

function favGame(): void { console.log("My Favourite game is Cricket."); }

29. Header: null explained

Question

What is type null and its use in TypeScript?

Why you Might Get Asked This

Nullable types model missing data. Interviewers check your ability to design functions that accept optional or absent values safely.

How to Answer

  • Define null as explicit absence.
  • Show union types like string | null and guard checks before use.
  • Give a sample function that handles both cases.

Example Answer

function getData(orgName: string | null) { if (orgName === null) console.log("Not enough values provided"); else console.log(orgName); }

30. Header: Object literal syntax

Question

Describe the syntax for creating objects in TypeScript.

Why you Might Get Asked This

Objects represent domain data; the interviewer wants to ensure you can annotate shapes so the compiler enforces correct property usage.

How to Answer

  • Show an inline object type annotation with property names and types.
  • Provide an initialized example consistent with the type.

Example Answer

const myObj: { name: string, desc: string } = { name: "GeeksforGeeks", desc: "A Computer Science Portal" };

31. Header: Optional object fields

Question

Can we specify the optional properties to TypeScript Object, if Yes, explain How?

Why you Might Get Asked This

This verifies you can model partial objects like partial updates or optional API fields without losing type safety.

How to Answer

  • Use ? after the property name in the object type.
  • Show object initialization missing that property and later assignment.

Example Answer

const myObj: { name: string, desc: string, est?: number } = { name: "GeeksforGeeks", desc: "A Computer Science Portal" }; myObj.est = 2008;

32. Header: undefined deeper look

Question

Explain the undefined type in TypeScript.

Why you Might Get Asked This

Getting undefined behavior right avoids runtime errors. Interviewers test if you know when undefined appears and how the compiler treats it.

How to Answer

  • Define undefined as the result of declared-but-uninitialized variables.
  • Mention hoisting and temporal dead zone differences for var/let/const in JS.
  • Note how strictNullChecks affects unions with undefined.

Example Answer

let x: number | undefined; // x is undefined until assigned

33. Header: Array behavior and typing

Question

Explain the behavior of arrays in TypeScript.

Why you Might Get Asked This

Arrays hold most collections; the interviewer wants to ensure you can type arrays and prevent accidental mixed types or runtime surprises.

How to Answer

  • Explain typed arrays allow only the declared element type.
  • Show an example that causes a type error when adding a different type.
  • Mention tuple alternatives for fixed-length mixed types.

Example Answer

const typedArray1: number[] = [1, 23, 28]; // adding "string" will error

34. Header: Compiling TypeScript files

Question

How can you compile a TypeScript file?

Why you Might Get Asked This

Basic workflow matters: they want to know you can run tsc or configure build tools and understand output JS generation.

How to Answer

  • Mention tsc filename.ts for single-file compile.
  • Note tsconfig.json for project-level configuration and build pipelines.

Example Answer

tsc filename.ts will produce filename.js. Use tsconfig.json to configure whole-project compilation.

35. Header: .ts vs .tsx distinctions

Question

Differentiate between the .ts and .tsx file extensions given to the TyppeScript file.

Why you Might Get Asked This

If you work with React, you must know when JSX is allowed. This shows you can pick correct file extensions and config.

How to Answer

  • .ts for plain TypeScript files without JSX.
  • .tsx for files that include JSX/React elements; compiler treats them differently.

Example Answer

Use .tsx when the file contains JSX, like React components; otherwise use .ts.

36. Header: Using the in operator

Question

What is "in" operator and why it is used in TypeScript?

Why you Might Get Asked This

The in operator helps guard object shapes at runtime and works as a type guard in narrow checks. Interviewers want to know you can safely check properties.

How to Answer

  • Explain in checks property existence: propName in object.
  • Use it to narrow union types that differ by a property.
  • Provide a short example.

Example Answer

if ("prop" in obj) { /* safe to access obj.prop */ }

37. Header: Union types explained

Question

Explain the union types in TypeScript?

Why you Might Get Asked This

Union types let you express multiple possible types for a value. This tests your ability to model flexible APIs while preserving type safety via narrowing.

How to Answer

  • Describe using | to combine types, e.g., string | number.
  • Explain you must narrow before using type-specific operations.
  • Give a simple example of function accepting string | number.

Example Answer

function format(x: string | number) { if (typeof x === "number") return x.toFixed(2); return x.trim(); }

38. Header: Type aliases to name types

Question

Explain type alias in TypeScript?

Why you Might Get Asked This

Type aliases let you simplify complex types and improve readability. Interviewers check whether you can reuse and compose types effectively.

How to Answer

  • Define type alias with the type keyword.
  • Show a union alias example and mention it does not create a new runtime construct.
  • Provide a brief usage.

Example Answer

type combinedType = number | boolean; let x: combinedType = 5;

39. Header: Static typing nuance

Question

Is TypeScript strictly statically typed language?

Why you Might Get Asked This

They want to confirm you know TypeScript is optionally typed and how any/unknown affect type checking. This shows practical understanding of typing levels.

How to Answer

  • Explain TypeScript is optionally statically typed; types are enforced when declared or inferred.
  • Mention any disables checking and unknown gives safer handling.

Example Answer

TypeScript enforces types when present, but you can opt out with any; inference gives many protections without explicit annotations.

40. Header: Template literals in TS

Question

Is template literal supported by TypeScript?

Why you Might Get Asked This

Template literals are common for string composition; interviewers check compatibility with JS features and typed string operations.

How to Answer

  • Confirm template literals are fully supported.
  • Show interpolation syntax with ${variable} and example usage.

Example Answer

const name = "Alice"; const s = `Hello, ${name}`;

41. Header: Typed arrow functions

Question

How to declare a arrow function in TypeScript?

Why you Might Get Asked This

Arrow functions are used in callbacks; typing parameters and return types avoids subtle runtime errors in callbacks and higher-order functions.

How to Answer

  • Show typed parameters and return type after ) :.
  • Provide a concise example returning a typed string.

Example Answer

const typedArrowFunc = (org_name: string, desc: string): string => `Organization: ${org_name}, Description: ${desc}`;

42. Header: Optional parameter functions

Question

How to define a function which accepts the optional parameters?

Why you Might Get Asked This

Optional parameters are used to create flexible APIs; interviewers want to know you can handle missing inputs safely.

How to Answer

  • Use ? to mark a parameter optional.
  • Provide conditional handling inside the function.
  • Give example calls with and without the optional arg.

Example Answer

function cricketer(c_name: string, runs?: number): void { console.log(runs ? `${c_name} scored ${runs}` : `${c_name} runs not available`); }

43. Header: noImplicitAny compiler guard

Question

Explain noImplicitAny in TypeScript.

Why you Might Get Asked This

This compiler option enforces explicit typing and avoids silent any types. Employers expect familiarity with strict options for code quality.

How to Answer

  • Explain it makes the compiler error when it must infer any for a variable or parameter.
  • Say it helps enforce explicit types and catches missing annotations.
  • Mention it is set in tsconfig.json.

Example Answer

Set "noImplicitAny": true in tsconfig to force explicit types when inference fails.

44. Header: Interfaces as contracts

Question

What are interfaces in TypeScript?

Why you Might Get Asked This

Interfaces define object shapes and contracts for classes, guiding API design and enabling structural typing. This checks modeling skills.

How to Answer

  • Define an interface as a named shape with property and method signatures.
  • Show it can be implemented by classes or used to type objects.
  • Give a small example.

Example Answer

interface Person { name: string; age: number; } const p: Person = { name: "Ann", age: 30 };

45. Header: For loops you will use daily

Question

In how many ways you can use the for loop in TypeScript?

Why you Might Get Asked This

Iteration patterns matter for correctness and readability. Interviewers want to see you can pick the right loop for arrays and generators.

How to Answer

  • List vanilla for (init; cond; inc), for...of for iterables, and array.forEach for callback style.
  • Mention when each is appropriate.

Example Answer

for (let i = 0; i < n; i++) {} for (const item of arr) {} arr.forEach(item => {});

46. Header: Typing arrays succinctly

Question

How do you give the type of Arrays?

Why you Might Get Asked This

Correct array typing prevents mixed-type errors and clarifies intent. This confirms you know syntax and readonly arrays.

How to Answer

  • Show const names: string[] = [...] form.
  • Show readonly string[] to prevent mutation.
  • Provide a push example and readonly error example.

Example Answer

const names: string[] = ["Nabendu"]; names.push("Dylan"); const readonlyNames: readonly string[] = ["A"]; // readonlyNames.push("B") // error

47. Header: Array type inference

Question

What is Type Inference in array?

Why you Might Get Asked This

Inference reduces boilerplate and catches mistakes; the question checks if you know when TS infers element types.

How to Answer

  • Explain the compiler infers element type from initial values.
  • Show a numeric array inferred as number[] and that further pushes must match.

Example Answer

const numbers = [1, 2, 3]; // inferred number[] numbers.push(4);

48. Header: Tuples for fixed mixed arrays

Question

What are tuples?

Why you Might Get Asked This

Tuples model fixed-length heterogeneous data like coordinate pairs. Interviewers want to see you can type mixed-element arrays precisely.

How to Answer

  • Define tuple as array with fixed length and element types in order.
  • Give an initialization example with correct types.

Example Answer

let ourTuple: [number, boolean, string]; ourTuple = [5, false, "Coding Hero was here"];

49. Header: Making tuples readonly

Question

What are readonly tuples?

Why you Might Get Asked This

Readonly tuples prevent accidental mutation and preserve index safety. The interviewer looks for awareness of immutability controls.

How to Answer

  • Explain adding readonly before the tuple type prevents push/pop and mutations.
  • Show example of push causing an error when readonly.

Example Answer

let ourTuple: readonly [number, boolean, string] = [5, false, "ok"]; // ourTuple.push('x') // error

50. Header: Object literal typing pattern

Question

How to give the types for Objects?

Why you Might Get Asked This

Structuring object types enforces property types and helps prevent runtime errors. This checks basic type annotation for records.

How to Answer

  • Show inline object type with property names and types.
  • Provide an initialized example that matches the shape.

Example Answer

const car: { brand: string, model: string, year: number } = { brand: "Tata", model: "Tiago", year: 2016 };

51. Header: Optional properties in object types

Question

How to have optional properties in Objects?

Why you Might Get Asked This

Optional keys model partial data and optional fields in DTOs.

Interviewers want to see you can safely type optional properties.

How to Answer

  • Use ? after the key name in the type annotation.
  • Provide an object initialized without that key.

Example Answer

const car: { brand: string, model: string, year?: number } = { brand: "Tata", model: "Punch" };

52. Header: Numeric enums quick guide

Question

Explain enum in TypeScript?

Why you Might Get Asked This

Checks if you can create readable, named constants and use them properly. Interviewers expect familiarity with default numeric behavior.

How to Answer

  • Define enum and note default numbering starts at 0.
  • Provide a usage example showing the numeric value.

Example Answer

enum allDirections { North, East, South, West } let currentDirection = allDirections.North; // logs 0

53. Header: String enums when clarity matters

Question

What is String enum?

Why you Might Get Asked This

String enums provide clearer runtime values and avoid confusion with numeric indices. Employers want readable logs and stable values.

How to Answer

  • Show an enum with explicit string assignments.
  • Explain that the runtime value is the string.
  • Give a short example.

Example Answer

enum allDirections { North = "North", East = "East" } let currentDirection = allDirections.North; // "North"

54. Header: Type aliases for clarity

Question

What are Type Aliases?

Why you Might Get Asked This

Type aliases reduce repetition and name complex types for readability. Interviewers want to see composition of types and reuse.

How to Answer

  • Define type alias with type keyword and show it can alias primitives or complex types.
  • Give a composite example using multiple aliases to build an object type.

Example Answer

type Year = number; type Car = { year: Year, type: string, model: string }; const car: Car = { year: 2005, type: "Tata", model: "Tiago" };

55. Header: Interfaces vs type aliases

Question

What are interfaces?

Why you Might Get Asked This

Interfaces are the idiomatic way to define object shapes and class contracts; the interviewer checks whether you know when to pick interfaces.

How to Answer

  • Describe interfaces as object-shaped contracts for properties and methods.
  • Show a simple interface and an object typed with it.

Example Answer

interface Square { length: number } const square: Square = { length: 20 };

56. Header: Extending interfaces

Question

How to extend interfaces?

Why you Might Get Asked This

Extension shows composition and reuse of contracts across objects and classes; it tests your design for inheritance and augmentation.

How to Answer

  • Use the extends keyword to create a new interface that adds properties.
  • Provide an example of base and extended interface with an object instantiation.

Example Answer

interface Square { length: number } interface ColorSquare extends Square { color: string } const square: ColorSquare = { length: 20, color: "blue" };

57. Header: Union types in practice

Question

What are Union types?

Why you Might Get Asked This

Union types model values that can be in multiple forms and require safe narrowing. Interviewers check if you can write functions that accept multiple types.

How to Answer

  • Explain use of | to allow multiple types.
  • Show that you must narrow by typeof or other guards to use type-specific operations.
  • Provide a usage example.

Example Answer

function printSuccessCode(code: string | number) { console.log(`My success code is ${code}.`) } printSuccessCode(200); printSuccessCode("200");

58. Header: Return type annotations

Question

How to give the return type in function?

Why you Might Get Asked This

Explicit return types document intent and prevent accidental changes; interviewers want enforced contracts for public APIs.

How to Answer

  • Place : Type after the function signature's ) to declare the return type.
  • Show examples for number and void returns.

Example Answer

function getSum(): number { return 24; } function printMessage(): void { console.log("Good Morning"); }

59. Header: Parameter type annotations

Question

How to give type of parameters in function?

Why you Might Get Asked This

Annotating parameters prevents passing wrong types and improves tooling. Interviewers expect clear signatures for maintainable APIs.

How to Answer

  • Annotate each parameter with : type.
  • Show a simple function that adds numbers and relies on those types.

Example Answer

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

60. Header: Optional, default, and rest params

Question

How to give optional, default and rest parameters in function?

Why you Might Get Asked This

Flexible function signatures are common; this checks your ability to combine optional and rest parameters safely.

How to Answer

  • Show optional parameter with ?, default parameter with = after the type, and rest params typed as T[].
  • Mention ordering rules: required, optional/default, rest.
  • Provide short examples.

Example Answer

function subtract(a: number, b: number, c?: number) { return a - b - (c || 0); } function multiply(a: number, b: number = 10) { return a * b; } function add(a: number, b: number, ...rest: number[]) { return a + b + rest.reduce((s, n) => s + n, 0); }

61. Header: Type assertions and casting

Question

What is casting in TypeScript?

Why you Might Get Asked This

Casting changes the compiler's view of a value type; interviewers want to ensure you use it appropriately and safely, not as a substitute for proper typing.

How to Answer

  • Explain casting (type assertion) with as or angle-bracket syntax.
  • Show example converting unknown to string to access .length.
  • Warn to prefer narrowing checks before asserting.

Example Answer

let y: unknown = 'Welcome'; console.log((y as string).length); // or console.log((<string>y).length);

62. Header: Class member typing

Question

How to give type of a variable in Class?

Why you Might Get Asked This

Typed class members document state and enable constructor checks and tooling. This checks your class-level typing habits.

How to Answer

  • Declare member: name: Type; at class scope.
  • Assign either in constructor or inline with an initializer.

Example Answer

class Developer { name: string; } const dev = new Developer(); dev.name = "Nabendu";

63. Header: Access modifiers explained

Question

What is public, private and protected in TypeScript classes?

Why you Might Get Asked This

Proper encapsulation prevents misuse of internals. Interviewers assess if you can design safe APIs with correct access controls.

How to Answer

  • Define public (default, accessible anywhere), private (only in class), and protected (class and subclasses).
  • Give brief examples showing constructor shorthand and inheritance.

Example Answer

class Developer { private name: string; constructor(name: string) { this.name = name; } public getName(): string { return this.name; } } class Rectangle { constructor(protected width: number, protected height: number) {} }

64. Header: readonly for immutable members

Question

What is the readonly keyword in reference to classes in TypeScript?

Why you Might Get Asked This

Readonly enforces immutability for members that should not change after construction. This demonstrates design for safety and intent.

How to Answer

  • Explain readonly prevents assignment after initialization.
  • Show usage with private or protected members and constructor initialization.

Example Answer

class Developer { private readonly name: string; constructor(name: string) { this.name = name; } public getName(): string { return this.name; } }

65. Header: Method overriding with override

Question

How to implement overriding in classes of TypeScript?

Why you Might Get Asked This

Overriding shows you can extend base behavior and safely change implementations while keeping contracts. Interviewers expect familiarity with the override modifier and super calls.

How to Answer

  • Implement a base class or interface method and provide a derived class method with override.
  • Use protected or public members when needed and call super if reusing base behavior.
  • Demonstrate toString override with accessible members.

Example Answer

interface Shape { getArea: () => number; } class Rectangle implements Shape { constructor(protected readonly width: number, protected readonly height: number) {} getArea(): number { return this.width * this.height; } toString(): string { return `Rectangle width is ${this.width} and height is ${this.height}`; } } class Square extends Rectangle { constructor(width: number) { super(width, width); } override toString(): string { return `Square width is ${this.width}`; } } const square = new Square(20); console.log(square.toString());

Related Reading

25+ TypeScript Intermediate Interview Questions

Blog image

1. Header: Never: the type that signals “this never happens”

Question

What is never type and its uses in TypeScript?

Why you Might Get Asked This

Interviewers use this to check your grasp of TypeScript’s control-flow typing and error handling. It shows whether you can reason about functions that do not complete normally or code paths that cannot occur.

How to Answer

  • Define never as the type for values that never occur, used for functions that never return or for impossible code paths.
  • Contrast never with void and any: void means a function may return undefined; never means it cannot return at all.
  • Give practical uses: throw helpers, exhaustive switch checks, and infinite loops; show a short code example.

Example Answer

function fail(msg: string): never {

throw new Error(msg);

}

function loopForever(): never {

while (true) {}

}

type Shape = { kind: "circle" } | { kind: "square" };

function assertNever(x: never): never {

throw new Error("Unexpected value: " + JSON.stringify(x));

}

function area(s: Shape) {

switch (s.kind) {

case "circle": return Math.PI * 1 * 1;

case "square": return 1;

default: return assertNever(s); // ensures exhaustiveness

2. Header: Enums made simple: constants with names

Question

Explain the working of enums in TypeScript?

Why you Might Get Asked This

Enums test whether you know TypeScript’s ways to model named constants and the trade offs between numeric and string enums. Interviewers want to see if you can pick the right pattern for maintainable code.

How to Answer

  • Define enums as a TypeScript feature for named constants; mention numeric defaults and string enums.
  • Show how values auto-increment and how to set custom initializers.
  • Note reverse-mapping for numeric enums and limitations compared to union types.

Example Answer

enum DemoEnum {

milk = 1,

curd,

butter,

cheese

}

const btr: DemoEnum = DemoEnum.butter;

console.log(btr); // 3

// String enum example:

enum Status {

Ready = "READY",

Running = "RUNNING",

Done = "DONE"

}

3. Header: Parameter destructuring: cleaner signatures, explicit types

Question

Explain the parameter destructuring in TypeScript.

Why you Might Get Asked This

This checks if you can write concise function signatures while keeping type safety for object parameters. It also indicates you understand inline type annotations and destructuring pitfalls.

How to Answer

  • Explain destructuring syntax for objects in parameters and how to annotate the destructured shape.
  • Show default values and optional properties with types.
  • Give an example where destructuring improves readability and prevents errors.

Example Answer

function getOrganisation(

{ org_name, org_desc }: { org_name: string; org_desc: string }

) {

console.log(`Organization Name: ${org_name}, Organization Description: ${org_desc}`);

}

getOrganisation({ org_name: "GeeksforGeeks", org_desc: "A Computer Science Portal." });

4. Header: Type inference: let the compiler fill in types

Question

Explain type inference in TypeScript.

Why you Might Get Asked This

Interviewers want to know if you rely on TypeScript’s inference to reduce noise without losing type safety. It reveals how you balance explicit annotations with inferred types for maintainable code.

How to Answer

  • Define inference as the compiler automatically assigning types from initializers or usage.
  • Show common cases: let/const initialization, function return types, and contextual typing.
  • Mention when to add explicit annotations: public API, widening, or ambiguous initial values.

Example Answer

let x = 3; // inferred as number

const name = "Alice"; // inferred as "Alice" literal type if const

function add(a: number, b = 2) { return a + b; } // return type inferred as number

5. Header: Modules: organize code with imports and exports

Question

What are modules in TypeScript?

Why you Might Get Asked This

This checks practical skills for structuring code across files and bundling. Interviewers expect you to know how exports and imports create scopes and share types, functions, and classes.

How to Answer

  • Define modules as file-based units that export values and types and import them where needed.
  • Explain export and import syntax and how modules provide encapsulation and reuse.
  • Mention module systems (ESM, CommonJS) and how tsconfig controls output.

Example Answer

export function product(a: number, b: number): number {

return a * b;

}

// In another file:

import { product } from "./multiply";

console.log(product(3, 4)); // 12

6. Header: Two module styles: internal vs external (file-based)

Question

In how many ways you can classify Modules?

Why you Might Get Asked This

Interviewers want to verify your familiarity with historical TypeScript module concepts and modern file-based modules used in real projects. That shows whether you can work in older code and modern builds.

How to Answer

  • State the two classes historically used: internal (namespaces) and external (file modules with import/export).
  • Recommend using external/file modules for modern code and mention namespaces for legacy or global scripts.
  • Note that external modules require at least one import or export per file.

Example Answer

TypeScript historically had internal modules (now called namespaces) for grouping code in one file. Today, external modules map to files using import/export and are the recommended pattern for apps and libraries.

7. Header: tsconfig.json: compiler control center

Question

What is the use of tsconfig.json file in TypeScript?

Why you Might Get Asked This

Hiring managers want to confirm you can configure projects, control compilation, and set options for type checking and module resolution. tsconfig is central to build setup and CI.

How to Answer

  • Explain that tsconfig.json declares the project root and TypeScript compiler options and files to include.
  • Mention common options: target, module, strict, outDir, and paths; and how editors and build tools read it.
  • Show a tiny example or describe how it simplifies tsc usage.

Example Answer

A minimal tsconfig.json:

{

"compilerOptions": {

"target": "ES2019",

"module": "ESNext",

"strict": true,

"outDir": "./dist"

},

"include": ["src"]

}

8. Header: Decorators: annotate and modify classes and members

Question

What are Decorators in TypeScript?

Why you Might Get Asked This

Decorators indicate knowledge of meta-programming patterns and frameworks that use them, such as Angular. Interviewers look for understanding of when decorators change runtime behavior versus adding metadata.

How to Answer

  • Define decorators as functions that can be attached to classes, methods, accessors, properties, and parameters to modify behavior or add metadata.
  • Note they are an experimental feature that requires "experimentalDecorators" in tsconfig and explain common use cases like dependency injection and logging.
  • Provide a short example of a class decorator and a method decorator.

Example Answer

function readonly(target: any, key: string, descriptor: PropertyDescriptor) {

descriptor.writable = false;

}

class Example {

@readonly

method() {

return 42;

}

}

9. Header: Source maps and tsc: how to debug TypeScript

Question

How to debug a TypeScript file?

Why you Might Get Asked This

Debugging TS to JS mapping shows practical skills for diagnosing runtime issues in browsers or Node. Interviewers want to see familiarity with source maps and tooling.

How to Answer

  • Explain generating source maps via tsconfig or tsc --sourceMap option so debuggers map JS back to TS.
  • Mention using editor debug adapters (VS Code), Chrome DevTools, or Node with --inspect and how sourcemaps enable breakpoints in .ts files.
  • Note how to check that compiled .js and .map files are served alongside the app.

Example Answer

Run tsc with source maps, or set "sourceMap": true in tsconfig.json, then open the site in Chrome, open DevTools, and set breakpoints directly in the .ts sources.

10. Header: Anonymous functions: unnamed, useful for callbacks

Question

Describe anonymous functions and their uses in TypeScript?

Why you Might Get Asked This

This reveals whether you can use functional patterns like callbacks, promises, and event handlers with proper typing. The interviewer checks your comfort with inline functions and arrow syntax.

How to Answer

  • Define anonymous functions as functions without a name, often used inline for callbacks and short logic.
  • Show typed anonymous function examples with arrow functions and how to type parameters and return values.
  • Demonstrate use cases: event handlers, array methods, and closure capture.

Example Answer

button.addEventListener("click", function (e: MouseEvent) {

console.log("clicked", e.clientX, e.clientY);

});

// Arrow function with types:

const doubled = [1,2,3].map((n: number): number => n * 2);

11. Header: Calling base constructors: super takes parameters

Question

Is it possible to call the constructor function of the base class using the child class?

Why you Might Get Asked This

This tests OOP fundamentals in TypeScript and how subclassing works at runtime. Interviewers check that you know super must be called before using this in derived constructors.

How to Answer

  • Confirm child classes call the base constructor using super(...args) inside their constructor.
  • Mention the requirement: call super before accessing this in derived classes.
  • Provide a short example with parameters passed through.

Example Answer

class Base {

constructor(public name: string) {}

}

class Child extends Base {

constructor(name: string, public age: number) {

super(name);

}

}

const c = new Child("Alex", 30);

12. Header: Bundle via tsc: combine files into one JS file

Question

How to combine multiple TypeScript files and convert them into single JavaScript file?

Why you Might Get Asked This

Interviewers want to see whether you know simple bundling options and legacy tsc features. This also tests awareness of when to use a bundler instead of tsc for production.

How to Answer

  • Explain tsc --outFile works for concatenating files when targeting module none or using namespaces; show syntax.
  • Warn that for modern module systems or node projects, use bundlers like webpack, Rollup, or esbuild instead.
  • Give the tsc command example.

Example Answer

tsc --outFile combined.js script1.ts script2.ts script3.ts

// For ES modules or node projects, prefer a bundler rather than --outFile.

13. Header: typeof operator: runtime type and compile-time aliasing

Question

Explain type of operator in TypeScript and where to use it.

Why you Might Get Asked This

This checks two related concepts JavaScript typeof at runtime and TypeScript’s typeof type queries for copying types. Interviewers want to see both practical and typing knowledge.

How to Answer

  • Describe JavaScript typeof for runtime checks and TypeScript typeof in type positions to refer to the type of a value.
  • Show an example of using typeof to create a typed alias from an existing variable.
  • Mention common use cases: deriving types from constants or functions to avoid duplication.

Example Answer

const numVar = 28;

type NumType = typeof numVar; // number

const strVar = "GFG";

type StrType = typeof strVar; // "GFG" if const, otherwise string

console.log(typeof numVar, typeof strVar); // runtime: number string

14. Header: tsc compile: turning TypeScript into JavaScript

Question

How you can compile a TypeScript file?

Why you Might Get Asked This

They want to confirm you can run the compiler and understand the build step required to run TypeScript. This shows practical familiarity with the toolchain.

How to Answer

  • State the basic command: tsc file.ts to compile a file, generating file.js by default.
  • Mention using tsconfig.json and running plain tsc to compile a whole project with configured options.
  • Note how to set target, module, and outDir either via CLI or tsconfig.

Example Answer

// Single file:

tsc script.ts

// Project build (uses tsconfig.json):

tsc

15. Header: OOP basics: supported principles

Question

Which principles of Object Oriented Programming are supported by TypeScript?

Why you Might Get Asked This

This checks your ability to model domain logic with classes, access control, and inheritance. Interviewers want to know you can implement OOP patterns in a typed system.

How to Answer

  • List supported principles: encapsulation (private/protected), inheritance (extends), polymorphism (subtyping, method overrides), and abstraction (interfaces and abstract classes).
  • Mention TypeScript’s additional type system features like interfaces and structural typing that aid design.

Example Answer

TypeScript supports abstraction via interfaces/abstract classes, encapsulation via public/private/protected, inheritance with extends, and polymorphism through subtyping and method overriding.

16. Header: Mixins: compose behavior without deep inheritance

Question

Explain Mixins in TypeScript

Why you Might Get Asked This

Mixins show your ability to compose behaviors and avoid brittle inheritance trees. Interviewers look for practical patterns to reuse code across unrelated classes.

How to Answer

  • Define mixins as functions that take a class and return a new class extended with extra behavior.
  • Show the typical pattern using generics and intersection types to preserve types.
  • Provide a short example composing two behaviors into a target class.

Example Answer

type Constructor<T = {}> = new (...args: any[]) => T;

function CanEat<TBase extends Constructor>(Base: TBase) {

return class extends Base { eat() { console.log("eating"); } };

}

class Animal {}

const EatingAnimal = CanEat(Animal);

const a = new EatingAnimal();

(a as any).eat();

17. Header: Immutable properties with readonly

Question

Is it possible to create the immutable Object properties in TypeScript?

Why you Might Get Asked This

This probes your knowledge of immutability patterns and compile-time guarantees. Interviewers want to see how you prevent accidental state changes.

How to Answer

  • Explain readonly modifier for properties and readonly arrays (ReadonlyArray<T>) to prevent reassignment.
  • Note that readonly is a compile-time constraint; runtime code can still mutate unless frozen.
  • Show an example of readonly in a class and an interface.

Example Answer

class Person {

readonly id: number;

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

}

const p = new Person(1);

// p.id = 2; // Error at compile time

const arr: ReadonlyArray<number> = [1, 2, 3];

18. Header: When to use a class versus an interface

Question

In what situation you should use a class and a interface?

Why you Might Get Asked This

This checks design judgment: when to define behavior versus a structural contract. Interviewers expect reasoning about runtime needs and type-only contracts.

How to Answer

  • Use an interface to describe shape and contract for objects and to enable structural typing without emitting runtime code.
  • Use a class when you need runtime instantiation, method implementations, inheritance, or encapsulation.
  • Mention that classes can implement interfaces to satisfy a contract while providing behavior.

Example Answer

interface IUser { name: string; email?: string; }

class User implements IUser {

constructor(public name: string, public email?: string) {}

}

19. Header: Classes vs interfaces: compare runtime and type-level roles

Question

What are the differences between the classes and the interfaces in TypeScript?

Why you Might Get Asked This

Interviewers want to confirm you know the difference between a runtime construct and a compile-time type. This affects how you design modules and APIs.

How to Answer

  • Explain that classes produce JavaScript at runtime with constructors and methods, while interfaces are erased at compile time and serve only for typing.
  • Note classes can have implementation and access modifiers; interfaces only declare the shape and can be extended or merged.
  • Mention that interfaces support declaration merging and are good for contracts across modules.

Example Answer

class Point { constructor(public x: number, public y: number) {} }

interface IPoint { x: number; y: number; }

const p: IPoint = new Point(1, 2); // structural typing allows this

20. Header: Class declaration: typed fields and methods

Question

How to declare a class in TypeScript?

Why you Might Get Asked This

This verifies you can model objects with typed members and constructors. Interviewers care about correct syntax and common patterns like parameter properties.

How to Answer

  • Show class syntax with typed fields, constructor, and methods; demonstrate parameter properties to reduce boilerplate.
  • Mention access modifiers (public/private/protected) and optional properties.
  • Provide a simple example illustrating state mutation and method return types.

Example Answer

class Cricketer {

constructor(public name: string, public runs: number) {}

thisMatchRuns(): number {

this.runs += 139;

return this.runs;

}

}

const player = new Cricketer("Joe", 100);

21. Header: Inheritance: extend classes and reuse logic

Question

How the inheritance can be used in TypeScript?

Why you Might Get Asked This

Interviewers want to know if you can reuse and extend behavior safely while keeping types intact. This shows understanding of subclassing and protected/private members.

How to Answer

  • Explain extends to create a subclass and how methods and properties are inherited.
  • Show how to override methods and call super for base behavior and constructors.
  • Mention how access modifiers affect visibility in derived classes.

Example Answer

class Parent { protected greet() { return "hi"; } }

class Child extends Parent {

sayHello() { return this.greet() + " from child"; }

}

const c = new Child();

console.log(c.sayHello());

22. Header: Visibility control: public, private, protected

Question

What are the different ways for controlling the visibility of member data?

Why you Might Get Asked This

This checks your ability to encapsulate state and design APIs that prevent misuse. Visibility affects maintainability and testability.

How to Answer

  • List the three modifiers: public (default, accessible anywhere), private (accessible only inside the declaring class), and protected (accessible inside class and subclasses).
  • Show examples and state how TypeScript enforces these at compile time.
  • Mention parameter property shorthand to declare visibility in constructors.

Example Answer

class Example {

public a: number;

private b: string;

protected c: boolean;

constructor(a: number, b: string, c: boolean) {

this.a = a; this.b = b; this.c = c;

}

}

23. Header: Declaration files: .d.ts for type consumers

Question

How to convert a .ts file into TypeScript Definition file?

Why you Might Get Asked This

This verifies you can package libraries with proper type exports so other consumers get type safety. Interviewers care about publishing and library consumption.

How to Answer

  • Explain tsc --declaration or "declaration": true in tsconfig to emit .d.ts alongside compiled JavaScript.
  • Mention how .d.ts files provide type contracts for consumers while hiding implementations.
  • Show the tsc command example.

Example Answer

tsc --declaration script.ts

// Or set in tsconfig.json:

// { "compilerOptions": { "declaration": true, "outDir": "lib" } }

24.Header: Static classes: why TypeScript does not need them

Question

Is it possible to create the static classes in TypeScript?

Why you Might Get Asked This

They want to see whether you understand static members and alternative patterns for grouping functions. This clarifies your familiarity with module-level code and class statics.

How to Answer

  • Explain TypeScript does not have a special static-class type, but classes can have static members and methods.
  • Note that for pure grouping without instantiation, use namespaces or plain modules/objects with exported functions.
  • Provide examples of static members and an alternative object-based pattern.

Example Answer

class Utils {

static sum(a: number, b: number) { return a + b; }

}

console.log(Utils.sum(2, 3));

// Or use a module-level export:

export const math = { sum: (a: number, b: number) => a + b };

25. Header: Conditional typing: choose types based on conditions

Question

Expalin conditional typing in TypeScript?

Why you Might Get Asked This

Conditional types test advanced typing skill and generic design for flexible APIs. Interviewers check whether you can build type-level logic that adapts based on input types.

How to Answer

  • Define conditional types using the syntax T extends U ? X : Y, and explain they evaluate at compile-time to select types.
  • Show examples: inferring element types, mapping unions, and distributive behavior over unions.
  • Mention utility types built on conditional types, like ReturnType and Extract.

Example Answer

type ElementType<T> = T extends (infer U)[] ? U : T;

type A = ElementType<string[]>; // string

type B = ElementType<number>; // number

type NonString<T> = T extends string ? never : T;

type Result = NonString<string | number>; // number

Related Reading

  • ASP.NET MVC Interview Questions
  • Leetcode Roadmap
  • Ansible Interview Questions
  • Deep Learning Interview Questions
  • NodeJS Interview Questions
  • System Design Interview Preparation
  • ML Interview Questions
  • LockedIn
  • Leetcode Alternatives
  • Selenium Interview Questions And Answers
  • Cybersecurity Interview Questions
  • Engineering Levels
  • Front End Developer Interview Questions
  • DevOps Interview Questions And Answers
  • Git Interview Questions
  • jQuery Interview Questions

30 Typescript Interview Questions for Experienced

Blog image

1. Header: Lock Down Nulls — enforce safer code with strict null checks

Question

How to enforce strict null checks in TypeScript?

Why you Might Get Asked This

Interviewers want to see you reduce runtime null and undefined errors and configure the compiler correctly. This shows familiarity with compiler options, tsconfig, and how types affect runtime safety.

How to Answer

  • Explain the compiler flag and tsconfig option that enable strict null checking.
  • Describe the difference in type behavior when the option is on versus off.
  • Mention practical effects on code and common migration steps.

Example Answer

You can enforce strict null checks in two ways:

  • provide the --strictNullChecks flag to the TypeScript (tsc) compiler
  • set the strictNullChecks property to true in the tsconfig.json configuration file.

When the flag is false, TypeScript ignores null and undefined values in the code. When it is true, null and undefined have their distinct types. The compiler throws a type error if you try to use them where a concrete value is expected.

2. Header: Static Classes? Why TypeScript skips that pattern

Question

Does TypeScript support static classes? If not, why?

Why you Might Get Asked This

The question probes object-oriented design knowledge and how TypeScript maps to Java/C# concepts. It reveals whether you can adapt patterns to JavaScript’s and TypeScript’s flexible module and object model.

How to Answer

  • State that TypeScript does not have a specific static class construct.
  • Explain that top-level functions and plain objects replace the need for static classes.
  • Note singletons and module patterns as practical alternatives.

Example Answer

TypeScript doesn’t support static classes, unlike the popular object-oriented programming languages like C# and Java.

These languages need static classes because all code, i.e., data and functions, need to be inside a class and cannot exist independently. Static classes provide a way to allow these functions without associating them with any objects.

In TypeScript, you can create any data and functions as simple objects without creating a containing class. Hence TypeScript doesn’t need static classes. A singleton class is just a simple object in TypeScript.

3. Header: Tell the compiler what you know — type assertions

Question

What are type assertions in TypeScript?

Why you Might Get Asked This

Interviewers want to confirm you can guide the type system when inference is insufficient and avoid unsafe casts. This checks practical handling of unknown or any values and working with DOM or third-party untyped APIs.

How to Answer

  • Define type assertions and why they exist when compiler inference is limited.
  • Show both as and angle-bracket syntaxes with short examples.
  • Clarify that assertions affect compile time only, not runtime behavior.

Example Answer

Sometimes, you as a programmer might know more about the type of a variable than TypeScript can infer. Usually, this happens when you know the type of an object is more specific than its current type. In such cases, you can tell the TypeScript compiler not to infer the type of the variable by using type assertions.

TypeScript provides two forms to assert the types.

as syntax:

let value: unknown = "Foo";

let len: number = (value as string).length;

<> syntax:

let value: unknown = "Foo";

let len: number = (<string>value).length;

Type assertions are similar to typecasting in other programming languages such as C# or Java. However, unlike those languages, there’s no runtime penalty of boxing and unboxing variables to fit the types. Type assertions simply let the TypeScript compiler know the type of the variable.

4. Header: Pulling values from tuples — tuple destructuring

Question

Explain how tuple destructuring works in TypeScript.

Why you Might Get Asked This

This verifies understanding of fixed-length arrays, destructuring syntax, and the type safety that follows. Interviewers check that you know how destructuring preserves element types and enforces assignment rules.

How to Answer

  • Describe assigning tuple elements to variables via = and how types flow.
  • Show example destructuring with type annotations and effects on later assignments.
  • Note that you cannot assign a different type to a destructured variable afterwards.

Example Answer

You can destructure tuple elements by using the assignment operator (=). The destructuring variables get the types of the corresponding tuple elements.

let employeeRecord: [string, number] = ["John Doe", 50000];

let [emp_name, emp_salary] = employeeRecord;

console.log(`Name: ${emp_name}`); // "Name: John Doe"

console.log(`Salary: ${emp_salary}`); // "Salary: 50000"

After destructuring, you can’t assign a value of a different type to the destructured variable. For example,

emp_name = true; // Type 'boolean' is not assignable to type 'string'.(2322)

5. Header: Fixed-shape arrays — understanding tuple types

Question

Explain the tuple types in TypeScript.

Why you Might Get Asked This

Interviewers test knowledge of fixed-length heterogeneous arrays and how TypeScript models them. This shows you understand when to use tuples versus arrays and how optional tuple elements work.

How to Answer

  • Define tuples as arrays with fixed element types and positions.
  • Show a correct example and a type error when types are mismatched.
  • Mention optional elements with ? since TypeScript 3.0.

Example Answer

Tuples are a special type in TypeScript. They are similar to arrays with a fixed number of elements with a known type. However, the types need not be the same.

// Declare a tuple type and initialize it

let values: [string, number] = ["Foo", 15];

// Type 'boolean' is not assignable to type 'string'.(2322)

// Type 'string' is not assignable to type 'number'.(2322)

let wrongValues: [string, number] = [true, "hello"]; // Error

Since TypeScript 3.0, a tuple can specify one or more optional types using the ? as shown below.

let values: [string, number, boolean?] = ["Foo", 15];

6. Header: Rename complex types — use type aliases

Question

What are type aliases? How do you create one?

Why you Might Get Asked This

The interviewer checks your ability to simplify and reuse union or complex types, improving readability and maintainability. This shows you can design clearer APIs and use aliases with generics.

How to Answer

  • Define type aliases as alternate names for types, not new runtime types.
  • Show syntax using type and a simple union example.
  • Mention use cases like unions, function signatures, and complex object shapes.

Example Answer

Type aliases give a new, meaningful name for a type. They don’t create new types but create new names that refer to that type.

For example, you can alias a union type to avoid typing all the types everywhere that value is being used.

type alphanumeric = string | number;

let value: alphanumeric = "";

value = 10;

7. Header: Combine types — intersection types explained

Question

What are intersection types?

Why you Might Get Asked This

This probes how you merge behaviors from multiple interfaces or types and design composite types for richer objects. Interviewers want to see fluency with structural typing and composition.

How to Answer

  • Define intersection types and the & operator semantics.
  • Give an example combining two interfaces into a single type.
  • Show how a value must satisfy all constituent types.

Example Answer

Intersection types let you combine the members of two or more types by using the ‘&’ operator. This allows you to combine existing types to get a single type with all the features you need.

The following example creates a new type Supervisor that has the members of types Employee and Manager.

interface Employee {

work: () => string;

}

interface Manager {

manage: () => string;

}

type Supervisor = Employee & Manager;

// john can both work and manage

let john: Supervisor;

8. Header: Accept multiple possibilities — union types

Question

What are union types in TypeScript?

Why you Might Get Asked This

Interviewers want to confirm you can model values that can take multiple shapes and handle them safely with narrowing. This reveals skill with discriminated unions and control flow analysis.

How to Answer

  • Define a union type using | and show a simple example.
  • Explain that values can be one of the listed types and assignment restrictions.
  • Mention how narrowing or type guards are needed for safe access to type-specific members.

Example Answer

A union type is a special construct in TypeScript that indicates that a value can be one of several types. A vertical bar (|) separates these types.

Consider the following example where the variable value belongs to a union type consisting of strings and numbers. The value is initialized to string “Foo”. Because it can only be a string or a number, we can change it to a number later, and the TypeScript compiler doesn’t complain.

let value: string | number = "Foo";

value = 10; // Okay

However, if we try to set the value to a type not included in the union types, we get the following error.

value = true; // Type 'boolean' is not assignable to type 'string | number'.(2322)

Union types allow you to create new types out of existing types. This removes a lot of boilerplate code as you don’t have to create new classes and type hierarchies.

9. Header: Anonymous functions — concise callbacks and IIFEs

Question

What are anonymous functions? Provide their syntax in TypeScript.

Why you Might Get Asked This

The interviewer checks familiarity with callbacks, higher-order functions, and immediately invoked function expressions used in module patterns. It confirms practical JavaScript skills within TypeScript code.

How to Answer

  • Define anonymous functions as functions without names used for callbacks.
  • Show a typical setTimeout callback and an IIFE example.
  • Note they are commonly used with arrow functions in modern code.

Example Answer

An anonymous function is a function without a name. Anonymous functions are typically used as callback functions, i.e., they are passed around to other functions, only to be invoked by the other function at a later point in time. For example,

setTimeout(function () {

console.log('Run after 2 seconds')

}, 2000);

You can invoke an anonymous function as soon as it’s created. It’s called ‘immediately invoked function execution (IIFE)’, For example:

(function() {

console.log('Invoked immediately after creation');

})();

10. Header: Abstract classes — partial implementations with contracts

Question

What are abstract classes? When should you use one?

Why you Might Get Asked This

This checks your ability to design reusable base classes that enforce behavior while supplying common code. Interviewers look for awareness of when to prefer abstract classes over interfaces.

How to Answer

  • Define abstract classes and abstract members; note they cannot be instantiated.
  • Show a subclass implementing abstract methods and using shared implementations.
  • Explain a use case where base behavior plus enforced overrides makes sense.

Example Answer

Abstract classes are similar to interfaces in that they specify a contract for the objects, and you cannot instantiate them directly. However, unlike interfaces, an abstract class may provide implementation details for one or more of its members.

An abstract class marks one or more of its members as abstract. Any classes that extend an abstract class have to provide an implementation for the abstract members of the superclass.

Here is an example of an abstract class Writer with two member functions. The write() method is marked as abstract, whereas the greet() method has an implementation. Both the FictionWriter and RomanceWriter classes that extend from Writer have to provide their specific implementation for the write method.

abstract class Writer {

abstract write(): void;

greet(): void {

console.log("Hello, there. I am a writer.");

}

}

class FictionWriter extends Writer {

write(): void {

console.log("Writing a fiction.");

}

}

class RomanceWriter extends Writer {

write(): void {

console.log("Writing a romance novel.");

}

}

const john = new FictionWriter();

john.greet(); // "Hello, there. I am a writer."

john.write(); // "Writing a fiction."

const mary = new RomanceWriter();

mary.greet(); // "Hello, there. I am a writer."

mary.write(); // "Writing a romance novel."

11. Header: Immutable properties — readonly for predictable state

Question

How to make object properties immutable in TypeScript? (hint: readonly)

Why you Might Get Asked This

This reveals understanding of immutability practices and type-level enforcement to prevent accidental state mutation. Employers value predictable data models and compile-time guarantees.

How to Answer

  • Show use of readonly on interface or class properties.
  • Explain that assignment is allowed only during initialization.
  • Give an example demonstrating a compile-time error on reassignment.

Example Answer

You can mark object properties as immutable by using the readonly keyword before the property name. For example:

interface Coordinate {

readonly x: number;

readonly y: number;

}

When you mark a property as readonly, it can only be set when you initialize the object. Once the object is created, you cannot change it.

let c: Coordinate = { x: 5, y: 15 };

c.x = 20; // Cannot assign to 'x' because it is a read-only property.(2540)

12. Header: Declaration files — .d.ts for type information

Question

What is a type declaration file?

Why you Might Get Asked This

Interviewers check that you can integrate untyped third-party JS with TypeScript and provide typing for libraries. This shows you know how to enable IntelliSense and safe consumption of external code.

How to Answer

  • Define .d.ts as files that declare types without implementations.
  • Explain their role when using untyped or JS libraries to provide compiler info.
  • Mention they produce no JS output and are referenced by tsconfig or triple-slash directives.

Example Answer

A typical TypeScript project references other third-party TypeScript libraries such as JQuery to perform routine tasks. Having type information for the library code helps you in coding by providing detailed information about the types, method signatures, etc., and provides IntelliSense.

A type declaration file is a text file ending with a .d.ts extension providing a way to declare the existence of some types or values without actually providing implementations for those values. It contains the type declarations but doesn’t have any source code. It doesn’t produce a .js file after compilation.

13. Header: Triple-slash directives — simple compiler hints at file top

Question

What are triple-slash directives?

Why you Might Get Asked This

The interviewer wants to confirm knowledge of legacy and low-level compiler directives and how file inclusion ordering or references work. This indicates familiarity with tsconfig, module resolution, and build outputs.

How to Answer

  • Describe triple-slash directives as single-line XML-style comments at file top.
  • Show the main use: /// <reference path="..." /> to include another file.
  • Note placement rules: only at the top, and how they affect outFile ordering.

Example Answer

Triple-slash directives are single-line comments that contain a single XML tag. TypeScript uses this XML tag as a compiler directive.

You can only place a triple-slash directive at the top of the containing file. Only single or multi-line comments can come before a triple-slash directive. TypeScript treats them as regular comments if it occurs in the middle of a code block, after a statement.

The primary use of triple-slash directives is to include other files in the compilation process. For example, the following directive instructs the compiler to include a file specified by the path in the containing TypeScript file.

/// <reference path="..." />

Triple-slash directives also order the output when using --out or --outFile. The output files are produced to the output file location in the same order as the input files.

14. Header: Using in to check object keys at runtime

Question

Explain the purpose of the ‘in’ operator.

Why you Might Get Asked This

This verifies knowledge of property existence checks at runtime and how they integrate with type narrowing or guards. It shows practical skills for defensive coding in TypeScript and JavaScript.

How to Answer

  • Define that in checks whether a property exists on an object and returns a boolean.
  • Provide a small example showing true and false results.
  • Mention its use in type guards when discriminating union shapes.

Example Answer

The in operator is used to find if a property is in the specified object. It returns true if the property belongs to the object. Otherwise, it returns false.

const car = { make: 'Hyundai', model: 'Elantra', year: 2017 };

console.log('model' in car); // true

console.log('test' in car); // false

15. Header: Implements clauses — enforce a class contract

Question

What are the ‘implements’ clauses in TypeScript?

Why you Might Get Asked This

Interviewers check your understanding of how classes adhere to interface contracts and enforce method signatures at compile time. This reveals design discipline and use of structural typing for predictability.

How to Answer

  • Explain that implements forces a class to satisfy an interface’s members.
  • Show that missing required members produce compiler errors.
  • Note that a class can implement multiple interfaces.

Example Answer

An implements clause is used to check that a class satisfies the contract specified by an interface. If a class implements an interface and doesn’t implement that interface, the TypeScript compiler issues an error.

interface Runnable {

run(): void;

}

class Job implements Runnable {

run() {

console.log("running the scheduled job!");

}

}

// Class 'Task' incorrectly implements interface 'Runnable'.

// Property 'run' is missing in type 'Task' but required in type 'Runnable'.(2420)

class Task implements Runnable {

perform() {

console.log("pong!");

}

}

A class can implement more than one interface. In this case, the class has to specify all the contracts of those interfaces.

16. Header: Limit values to exact strings — string literal types

Question

What are string literal types?

Why you Might Get Asked This

The interviewer wants to see how you restrict values to specific strings for safer APIs, often used instead of enums or for discriminated unions. It shows attention to precise types and better tooling support.

How to Answer

  • Define string literal types and show they only accept the exact string.
  • Provide an example of a union of string literals as function parameter.
  • Explain this helps with compile-time checks and autocompletion.

Example Answer

In TypeScript, you can refer to specific strings and numbers as types.

let foo: "bar" = "bar";

// OK

foo = "bar";

// Error: Type '"baz"' is not assignable to type '"bar"'.(2322)

foo = "baz";

String literal types on their own are not that useful. However, you can combine them into unions. This allows you to specify all the string values that a variable can take, in turn acting like enums. This can be useful for function parameters.

function greet(name: string, greeting: "hi" | "hello" | "hola") {

// ...

}

greet("John", "hello");

// Error: Argument of type '"Howdy?"' is not assignable to parameter of type '"hi" | "hello" | "hola".(2345)

greet("Mary", "Howdy?");

String literal types can help us spell-check the string values.

17. Header: Build strings at the type level — template literal types

Question

What are template literal types?

Why you Might Get Asked This

This checks advanced type construction skills and how you generate many specific string literal types from unions. Interviewers want to see creative uses of the type system for API constraints.

How to Answer

  • Define template literal types as combining literal types with template syntax.
  • Show an example that composes types into new string literal unions.
  • Mention that unions expand to all combinations for exhaustive typing.

Example Answer

Template literal types are similar to the string literal types. You can combine them with concrete, literal types to produce a new string literal type. Template literal types allow us to use the string literal types as building blocks to create new string literal types.

type Point = "GraphPoint";

// type Shape = "Grid GraphPoint"

type Shape = `Grid ${Point}`;

Template literal types can also expand into multiple strings via unions. It helps us create the set of every possible string literal that each union member can represent.

type Color = "green" | "yellow";

type Quantity = "five" | "six";

// type ItemTwo = "five item" | "six item" | "green item" | "yellow item"

type ItemOne = `${Quantity | Color} item`;

18. Header: Inheritance basics — extend and reuse class behavior

Question

Explain the concept of inheritance in TypeScript.

Why you Might Get Asked This

Interviewers test object-oriented design knowledge and how TypeScript implements classical inheritance with extends. They want to see how you reuse code and override behavior correctly.

How to Answer

  • Define inheritance and the extends keyword and single inheritance limitation.
  • Show a base class with properties and methods and a subclass using super.
  • Provide example showing both inherited and subclass-specific methods.

Example Answer

Inheritance allows a class to extend another class and reuse and modify the behavior defined in the other class. The class which inherits another class is called the derived class, and the class getting inherited is called the base class.

In TypeScript, a class can only extend one class. TypeScript uses the keyword ‘extends’ to specify the relationship between the base class and the derived classes.

class Rectangle {

length: number;

breadth: number

constructor(length: number, breadth: number) {

this.length = length;

this.breadth = breadth

}

area(): number {

return this.length * this.breadth;

}

}

class Square extends Rectangle {

constructor(side: number) {

super(side, side);

}

volume() {

return "Square doesn't have a volume!"

}

}

const sq = new Square(10);

console.log(sq.area()); // 100

console.log(sq.volume()); // "Square doesn't have a volume!"

In the above example, because the class Square extends functionality from Rectangle, we can create an instance of square and call both the area() and volume() methods.

19. Header: Types that pick based on conditions — conditional types

Question

What are conditional types? How do you create them?

Why you Might Get Asked This

This probes knowledge of advanced generics and how to map types based on relationships. Interviewers look for the ability to create flexible, type-safe APIs and transformations.

How to Answer

  • Define the conditional type syntax C extends B ? X : Y.
  • Explain it selects one of two types based on a type relationship.
  • Mention common uses like distributive conditional types and utility-type implementations.

Example Answer

A conditional type allows you to dynamically select one of two possible types based on a condition. The condition is expressed as a type relationship test.

C extends B ? TypeX : TypeY

Here, if type C extends B, the value of the above type is TypeX. Otherwise, it is TypeY.

20. Header: The Function type — generic callable values

Question

What is the Function type in TypeScript?

Why you Might Get Asked This

Interviewers check awareness of broad function typings versus specific signatures. This shows you understand why using Function or any loses safety and how to type callbacks precisely.

How to Answer

  • State that Function is a global type with callable behavior and standard methods.
  • Note that a value typed as Function can be called but returns any by default.
  • Recommend preferring specific call signatures or generics for safer typing.

Example Answer

Function is a global type in TypeScript. It has properties like bind, call, and apply, along with the other properties present on all function values.

function perform(fn: Function) {

fn(10);

}

You can always call a value of the Function type, and it returns a value of ‘any’ type.

21. Header: Utility types at your fingertips — Partial, Required, Readonly, Record

Question

List some of the utility types provided by TypeScript and explain their usage.

Why you Might Get Asked This

Interviewers want to see you leverage built-in mapped types to transform shapes quickly and avoid boilerplate. This indicates practical experience writing generic code and handling object transforms.

How to Answer

  • Name common utility types and give concise descriptions of their effects.
  • Provide quick examples for Partial, Required, Readonly, and Record.
  • Mention these are globally available and used in many codebases and libraries.

Example Answer

TypeScript provides various utility types that make common type transformations easy. These utility types are available globally. Here are some of the essential utility types included in TypeScript.

Utility Type Description

Partial<Type> Constructs a type with all properties of Type set to optional.

Required<Type> Constructs a type consisting of all properties of Type set to required.

Readonly<Type> Constructs a type with all properties of Type set to readonly.

Record<Keys, Type> Constructs an object type with property keys are of type Keys, and values are Type.

22. Header: Visibility control — public, protected, private

Question

Explain the various ways to control member visibility in TypeScript.

Why you Might Get Asked This

The question explores encapsulation and API design in classes and whether you use access modifiers to enforce invariants. It shows knowledge of subclass visibility and internal state protection.

How to Answer

  • List public, protected, and private and define their access scopes.
  • Note public is default, protected allows subclass access, private restricts to the class.
  • Give small examples or mention compilation-time enforcement.

Example Answer

TypeScript provides three keywords to control the visibility of class members, such as properties or methods.

public: You can access a public member anywhere outside the class. All class members are public by default.

protected: A protected member is visible only to the subclasses of the class containing that member. Outside code that doesn’t extend the container class can’t access a protected member.

private: A private member is only visible inside the class. No outside code can access the private members of a class.

23. Header: Walk the collection — for loop variants you should know

Question

Explain the different variants of the for loop in TypeScript.

Why you Might Get Asked This

Interviewers want to confirm you know basic iteration patterns over arrays and collections and when to use each form. This shows practical skills in writing readable, idiomatic code.

How to Answer

  • List classic for, forEach callback, and for..of with short syntax examples.
  • Explain scenarios where each is appropriate like index access or early return.
  • Mention TypeScript type support remains the same across these variants.

Example Answer

TypeScript provides the following three ways to loop over collections.

‘for’ loop

let values = [10, "foo", true];

for(let i=0; i<values.length; i++) {

console.log(values[i]); // 10, "foo", true

}

‘forEach’ function

let values = [10, "foo", true];

values.forEach(val => {

console.log(val); // 10, "foo", true

})

‘for..of’ statement

let values = [10, "foo", true];

for (let val of values) {

console.log(val); // 10, "foo", true

}

24. Header: Unique object keys — the symbol primitive

Question

Explain the symbol type in TypeScript.

Why you Might Get Asked This

The interviewer checks knowledge of ES6 primitives and how to create private-like keys or metadata properties. This tests familiarity with unique property keys and iteration behavior.

How to Answer

  • Define Symbol as an ES6 primitive supported by TypeScript.
  • Show how to create symbols with Symbol() or Symbol("desc") and uniqueness behavior.
  • Mention use cases like unique object keys and preventing name collisions.

Example Answer

Symbols were introduced in ES6 and are supported by TypeScript. Similar to numbers and strings, symbols are primitive types. You can use Symbols to create unique properties for objects.

You can create symbol values by calling the Symbol() constructor, optionally providing a string key.

let foo = Symbol();

let bar = Symbol("bar"); // optional string key

A key characteristic of symbols is that they are unique and immutable.

let foo = Symbol("foo");

let newFoo = Symbol("foo");

let areEqual = foo === newFoo;

console.log(areEqual); // false, symbols are unique

25. Header: Safe deep access — optional chaining with ?.

Question

Explain how optional chaining works in TypeScript.

Why you Might Get Asked This

The question confirms you can write resilient code that guards against nulls without verbose checks. It shows an understanding of modern syntax for property access and method invocation.

How to Answer

  • Define ?. as the optional chaining operator that short-circuits on null or undefined.
  • Show an example replacing verbose conditional checks with a single expression.
  • Note it returns undefined when a link in the chain does not exist.

Example Answer

Optional chaining allows you to access properties and call methods on them in a chain-like fashion. You can do this using the ‘?.’ operator.

TypeScript immediately stops running some expression if it runs into a ‘null’ or ‘undefined’ value and returns ‘undefined’ for the entire expression chain.

Using optional chaining, the following expression

let x = foo === null || foo === undefined ? undefined : foo.bar.baz();

can be expressed as:

let x = foo?.bar.baz();

26. Header: Overloads for multiple call signatures

Question

Provide the TypeScript syntax to create function overloads.

Why you Might Get Asked This

Interviewers test the ability to present multiple API surface signatures while keeping a single implementation. This shows you can design ergonomics and maintain type safety for varying argument shapes.

How to Answer

  • Show overload signatures above a single implementation signature.
  • Explain the implementation must be compatible but is not directly callable externally.
  • Provide a concise example with two overloads and one implementation.

Example Answer

Function overloading allows us to define multiple functions with the same name, as long as their number of parameters or the types of parameters are different.

The following example defines two overloads for the function buildDate. The first overload takes a number as a parameter, whereas the second takes three numbers as parameters. These are called overload signatures.

The body of the function also called an implementation signature, follows the overload signatures. You can’t call this signature directly, as it’s not visible from the outside. It should be compatible with the overload signatures.

function buildDate(timestamp: number): Date;

function buildDate(m: number, d: number, y: number): Date;

function buildDate(mOrTimestamp: number, d?: number, y?: number): Date {

if (d !== undefined && y !== undefined) {

return new Date(y, mOrTimestamp, d);

} else {

return new Date(mOrTimestamp);

}

}

const d1 = buildDate(87654321);

const d2 = buildDate(2, 2, 2);

27. Header: Let the compiler infer types — type inference

Question

What is meant by type inference?

Why you Might Get Asked This

The interviewer checks how you rely on the compiler to infer types to reduce verbosity while preserving safety. This shows familiarity with TypeScript ergonomics and common patterns.

How to Answer

  • Define type inference as the compiler deriving types when explicit annotations are omitted.
  • Give a simple initialized variable example where the type is known from the initializer.
  • Note that inference works for function return types and generics as well.

Example Answer

TypeScript can infer the type of a variable when you don’t provide an explicit type. This is known as type inference. This is usually done when the variables or parameters are initialized during the declaration.

For example, TypeScript knows that the variable foo is a string, even though we don’t mention string as a type.

let foo = "this is a string";

console.log(typeof foo); // "string"

28. Header: Context matters — contextual typing for safer callbacks

Question

What is meant by contextual typing?

Why you Might Get Asked This

Interviewers test whether you understand how TypeScript uses surrounding information to infer types for expressions, improving tool support without verbose annotations. This shows familiarity with DOM and callback typings.

How to Answer

  • Define contextual typing as inference based on the usage location or expected type.
  • Show the example of assigning a function to window.onmousedown to infer event parameter type.
  • Explain how this prevents accessing non-existent properties without errors.

Example Answer

When the TypeScript compiler uses the location (or context) of a variable to infer its type, it’s called contextual typing.

In the following example, TypeScript uses the Window.onmousedown function type information to infer the type of the function expression on the right-hand side of the assignment. This allows it to infer the type of the e parameter, which does have a button property but not a property named foo.

window.onmousedown = function (e) {

console.log(e.button); //<- OK

console.log(e.foo); //<- Error!

};

29. Header: noImplicitAny — force explicit types where inference is any

Question

What is the purpose of noImplicitAny?

Why you Might Get Asked This

This confirms awareness of compiler strictness options that prevent accidental any usage and improve long term safety. Interviewers expect familiarity with tsconfig and migration strategies.

How to Answer

  • Define noImplicitAny as a tsconfig option that errors when the compiler infers any.
  • Show an example where a parameter without a type gets implicit any and causes problems at runtime.
  • Explain that enabling it forces explicit types and reduces bugs from unexpected values.

Example Answer

Usually, when we don’t provide any type on a variable, TypeScript assumes ‘any’ type. For example, TypeScript compiles the following code, assuming the parameter ‘s’ is of any type. It works as long as the caller passes a string.

function parse(s) {

console.log(s.split(' '));

}

parse("Hello world"); // ["Hello", "world"]

However, the code breaks down as soon as we pass a number or other type than a string that doesn’t have a split() method on it. For example,

function parse(s) {

console.log(s.split(' ')); // [ERR]: s.split is not a function

}

parse(10);

noImplicitAny is a compiler option that you set in the tsconfig.json file. It forces the TypeScript compiler to raise an error whenever it infers a variable is of any type. This prevents us from accidentally causing similar errors.

Parameter 's' implicitly has an 'any' type.(7006)

function parse(s) {

console.log(s.split(' ')); // [ERR]: s.split is not a function

}

30. Header: Define object shape — what an interface provides

Question

What is an interface?

Why you Might Get Asked This

Interviewers want to confirm you can define contracts, enforce shapes, and use structural typing for loose coupling. This tests API design skills and type-driven development practices.

How to Answer

  • Define an interface as a compile-time contract describing object shape and operations.
  • Show how to declare and use an interface for parameters and variables.
  • Mention interfaces support duck typing and can describe classes, functions, or object literals.

Example Answer

An interface defines a contract by specifying the type of data an object can have and its operations. In TypeScript, you can specify an object’s shape by creating an interface and using it as its type. It’s also called “duck typing”.

In TypeScript, you can create and use an interface as follows:

interface Employee {

name: string;

salary: number;

}

function process(employee: Employee) {

console.log(`${employee.name}'s salary = ${employee.salary}`);

}

let john: Employee = {

name: "John Doe",

salary: 150000

}

process(john); // "John Doe's salary = 150000"

Interfaces are an effective way to specify contracts within your code as well as outside your code.

Related Reading

  • RPA Interview Questions
  • Angular 6 Interview Questions
  • Python Basic Interview Questions
  • Java Selenium Interview Questions
  • Coding Interview Platforms
  • Jira Interview Questions
  • Best Job Boards For Software Engineers
  • Technical Interview Cheat Sheet
  • Common C# Interview Questions
  • Software Engineer Interview Prep
  • Coding Interview Tools
  • Leetcode Cheat Sheet
  • Questions To Ask Interviewer Software Engineer

Nail Coding Interviews with our AI Interview Assistant − Get Your Dream Job Today

Interview Coder: Stop Grinding LeetCode and Prepare Smarter

Interview Coder is an AI powered study and coding coach built for developers who want results without wasting months on repetitive problem sets. It focuses on concept mastery, pattern recognition, and on demand hints so you spend less time memorizing and more time thinking. The goal is efficient learning that transfers to real interviews and real code.

How Interview Coder Helps You Learn TypeScript Interview Questions

Use it to practice type annotations, interfaces, generics, union and intersection types, mapped types, conditional types, keyof, type guards, and utility types. The assistant explains type inference, type narrowing, strictNullChecks, and declaration files with code examples you can run locally. It flags anti patterns and shows how to rewrite JavaScript into idiomatic TypeScript.

Real Time Coaching Designed for Practice Sessions not Cheating

Interview Coder gives step by step hints, test case suggestions, and runtimes for algorithms so you can iterate, debug, and learn. It integrates with your editor and terminal for offline drills and mock interviews while respecting interview rules and code of conduct. You practice writing types, handling promises with async await, and designing typed APIs without shortcuts that undermine your growth.

Features that Accelerate Mastery of TypeScript Concepts

Interactive code explanations that break down generics, higher order types, tuples, enums, and decorators. Automated test case generation to explore edge cases and async behavior. Performance checks for Big O reasoning and memory use so you can defend complexity choices in an interview. Each feature maps to common TypeScript interview questions about typing strategies and runtime behavior.

How Interview Coder Trains You on System Design Questions that Show up With TypeScript

Practice building typed modules, defining public API types, and using namespaces or ES modules with tsconfig rules. Simulate backend to frontend typing with declaration merging, module resolution, and ambient types. Learn how to model data with interfaces and mapped types for scalable code.

Learn to Explain Your Code Clearly During Interviews

Interviewers ask about tradeoffs, type safety, and maintainability. Interview Coder helps you craft concise explanations for design choices, how conditional types enable flexible APIs, and when to use structural typing instead of nominal patterns. Practice rhetorical moves like walking through type inference or showing why a union type simplifies error handling.

Targeted Drills for common TypeScript interview Question Categories

Algorithmic problems with typed implementations, debugging exercises involving null and unknown, and refactors that replace any with concrete types. You also get drills on Promise typing, async iterator patterns, and DOM type interfaces to prepare for frontend questions. Each drill ties to the exact wording you might see in an interview.

Ethical Rules and Compliance Baked into the Product

Interview Coder includes an ethics mode that disables any live answers during real interviews and focuses full power on mock interviews and post interview analysis. It encourages transparency with interviewers and supports prep that improves your skills rather than hides gaps. Policies and usage guides are part of onboarding.

How Teams and Candidates Measure Progress

Track improvements on type safety, test coverage, and problem classes solved with typed solutions. See metrics for time to correct solution, number of type errors reduced, and complexity reasoning scores. Use those metrics to prepare targeted learning plans and to practice common TypeScript interview questions more efficiently.

Integrations and Workflow Friendly Setup

Works with VS Code, WebStorm, and common terminals. Use local TypeScript compiler settings, custom tsconfig, and declaration files so practice mirrors your real stack. The assistant outputs runnable snippets and test runners that match how you code in production.

Common Interview Question Prompts you Will Master Here

Can you write a generic function to map over a tuple and preserve types Are mapped types suitable for this API How do you type a Promise that resolves to a union How do you narrow types safely at runtime with type guards These prompts become routine through guided repetition.

Start Practicing with Confidence and Clear Explanations

Choose a learning path focused on fundamentals or advanced types. Run timed mock interviews, review targeted feedback, and iterate on weak spots like conditional types or decorator usage. Use the tool to sharpen explanations and code, not to hide shortcomings.

Interview Coder - AI Interview Assistant Logo

Ready to Pass Any SWE Interviews with 100% Undetectable AI?

Start Your Free Trial Today