TypeScript interview questions test whether you can use static types to catch bugs before code runs: core types, the type system, generics, functions and classes, and the way you configure a real project. Below are the 40 questions I would prepare for, grouped from basic to advanced, each with a short answer and a code example you can compile.
In my work on web applications, I have seen strong typing cut bugs and make refactoring across teams safer. Most front-end and full-stack job postings I see now list TypeScript as a core requirement, and Microsoft, Google, Airbnb, and Netflix all use it in React, Angular, and Node.js codebases.
The answers reflect TypeScript 7.0, the Go-based compiler Microsoft released in July 2026, and the stricter defaults it kept from TypeScript 6.0.
Basic TypeScript Interview Questions
Basic TypeScript interview questions check that you know why TypeScript exists and how its core types behave.
1. Why use TypeScript over JavaScript?
TypeScript adds static typing and compile-time error checking, which helps developers detect bugs early and make codebases more predictable.
Types also document what each function expects, so large codebases stay easier to change.
2. What problems does TypeScript solve?
TypeScript addresses JavaScript’s weaknesses in type safety, scalability, and readability.
Enforcing clear type definitions prevents subtle runtime bugs and makes refactoring safer.
3. What are the main benefits of using static typing in TypeScript?
Static typing improves code reliability, auto-completion, and developer productivity.
It helps with early detection of type errors and allows IDEs to provide richer tooling support.
4. What are type annotations and why are they useful?
Type annotations allow developers to declare variable types explicitly.
This improves code readability and reduces runtime errors.
Here is an example:
let username:string="DataCamper";let age:number=25;let isAdmin:boolean=true;Powered by
In the above code, the compiler ensures that only the correct type can be assigned to each variable.
For example, if you try to assign a string to age, TypeScript will throw an error, which helps catch mistakes early.
Explicit typing is especially important for function parameters, return types, and API contracts, as it communicates expectations to other developers.
5. What is type inference in TypeScript?
TypeScript can automatically infer types based on assigned values.
This means you don’t always need to explicitly declare a type. TypeScript figures it out for you.
Here is an example:
let count =10;// inferred as number
count ="hello";// Error: Type 'string' is not assignable to type 'number'Powered by
In this example, TypeScript infers that count must be a number based on its initial value, so assigning a string later causes a compile-time error.
Best practices for type inference include:
Use explicit types for exported functions, classes, and interfaces to provide clear contracts.
Allow inference for local variables when the type is obvious.
Avoid using any unless absolutely necessary, as it bypasses TypeScript’s safety features.
6. How does TypeScript handle arrays, tuples, and enums?
TypeScript allows developers to enforce strict types on arrays, tuples, and enums to improve clarity and prevent runtime errors.
Here is a typed array example:
let scores:number[]=[95,80,85];
scores.push(100);// OK
scores.push("A+");// ErrorPowered by
A typed array only accepts elements of its declared type.
Tuples define fixed-length arrays with specific types for each position.
They are useful for structured data where the order and type of elements matter.
Here is an enum example:
enum Status {
Active,
Inactive,
Pending,}let currentStatus: Status = Status.Active;Powered by
Enums provide named constants, improving readability and reducing invalid values.
They are especially useful for status codes, roles, and configuration options.
A common 2026 follow-up is whether you would still use an enum. Enums generate runtime code, so Node.js type stripping and the erasableSyntaxOnly compiler flag reject them. Many teams use an as const object with a matching union type instead:
const Status ={
Active:"active",
Inactive:"inactive",
Pending:"pending",}asconst;typeStatus=(typeof Status)[keyoftypeof Status];// "active" | "inactive" | "pending"let currentStatus: Status = Status.Active;Powered by
7. What is the difference between any, unknown, and never types?
The following table highlights the key differences between the any, unknown, and never types in TypeScript.
Type
Description
any
Disables type checking entirely, allowing any value.
unknown
Safer alternative to any, you must check the type before using it.
never
Represents values that never occur (e.g., functions that always throw).
Here is an example:
functionfail():never{thrownewError("Something went wrong");}Powered by
A tip would be to prefer unknown over any to maintain type safety while retaining flexibility.
8. What is the difference between null and undefined in TypeScript?
The key differences between null and undefined are:
undefined means a variable has been declared but not assigned a value.
null is an explicit value meaning no value.
TypeScript's strictNullChecks mode treats them as separate types, which prevents accidental null-related bugs.
Here is an example:
let a:string|null=null;let b:string|undefined=undefined;Powered by
9. What does the strict compiler option do?
The strict flag turns on all of TypeScript’s strict type-checking rules. Since TypeScript 6.0, it is on by default, so a new project gets these checks unless you set "strict": false. The rules include:
strictNullChecks: Keeps null and undefined out of other types unless you allow them, which prevents null reference errors.
noImplicitAny: Reports an error when TypeScript cannot infer a type and would fall back to any, such as an untyped function parameter.
strictFunctionTypes: Checks function parameters contravariantly, catching unsafe function assignments (see question 27).
strictBindCallApply: Checks the arguments passed to bind, call, and apply.
strictPropertyInitialization: Requires class properties to be assigned in the constructor.
useUnknownInCatchVariables: Types the error in a catch clause as unknown instead of any.
Together, these checks catch null references and loose function types before they reach production.
TypeScript Type System Interview Questions
Let’s now look at some key TypeScript type system concepts commonly discussed in technical interviews.
10. What is the difference between interfaces and type aliases in TypeScript?
Both interfaces and type aliases describe the shape of objects, but they serve slightly different purposes.
Interfaces can be extended using extends, which makes them ideal for hierarchical object models.
Type aliases can represent unions, intersections, primitives, and more complex composite types.
Here is an example:
interfacePerson{
name:string;
age:number;}typeEmployee={
name:string;
department:string;};Powered by
Use interfaces when defining object shapes or class contracts.
Use type aliases when you need flexible, composable types like unions or intersections.
11. What are union and intersection types in TypeScript?
Union types allow a variable to hold multiple possible types, while intersection types combine multiple types into one.
Here is a union example:
let id:string|number;
id ="abc";// OK
id =123;// OKPowered by
Here is an intersection example:
typeAdmin={ name:string};typePermissions={ canEdit:boolean};typeAdminUser= Admin & Permissions;Powered by
Union types are often used in function parameters.
Intersection types are common in complex object compositions.
12. What is type narrowing, and how do type guards work?
Type narrowing lets TypeScript infer a more specific type based on control flow.
Here is an example:
functionprintId(id:string|number){if(typeof id ==="string"){console.log(id.toUpperCase());}else{console.log(id.toFixed());}}Powered by
Type guards ensure safe runtime operations by verifying the type before performing specific actions.
You can use:
typeof: for primitives
instanceof: for classes
Custom type guards: functions that return a type predicate such as pet is Fish
Type guards improve type safety and reduce runtime errors.
13. What are literal types and discriminated unions in TypeScript?
Literal types restrict a variable to a specific set of predefined values.
Here is an example:
let direction:"up"|"down"|"left"|"right";Powered by
Discriminated unions combine literal types with object variants for pattern matching.
Discriminated unions allow safe branching on object types and simplify logic in complex applications.
14. What are keyof, typeof, and in in TypeScript?
These operators let you build new types from existing types and values.
keyof: gets the property names of a type
typeof: gets the type of a value
in: used in mapped types
Here is an example:
interfaceUser{
name:string;
age:number;}typeUserKeys=keyof User;// "name" | "age"const person ={ name:"Alice", age:25};typePersonType=typeof person;// { name: string; age: number }Powered by
15. What are index signatures in TypeScript?
Index signatures allow objects with dynamic keys.
Here is an example:
interfaceErrors{[key:string]:string;}const messages: Errors ={
email:"Invalid email",
password:"Required"};Powered by
These are used for dictionaries, map-like objects, or dynamic configuration patterns.
16. What is structural typing in TypeScript?
Structural typing (duck typing) means types are compatible based on their structure, not their name.
Here is an example:
interfacePoint{ x:number; y:number;}let p ={ x:10, y:20, z:30};let q: Point = p;// OK because structural matchPowered by
This makes TypeScript flexible and works well with JavaScript patterns.
17. What is declaration merging in TypeScript?
Declaration merging happens when TypeScript combines multiple declarations with the same name.
Here is an example merging two interfaces:
interfaceUser{ name:string;}interfaceUser{ age:number;}const u: User ={ name:"Rob", age:30};// mergedPowered by
This is useful when extending third-party types or augmenting libraries.
Advanced TypeScript Interview Questions
Here are advanced TypeScript interview questions and answers.
18. What are generics in TypeScript, and why are they useful?
Generics allow you to write reusable, type-safe functions and classes that work with multiple data types.
Here is a generic function example:
functionidentity<T>(value:T):T{return value;}let output =identity<string>("DataCamp");let outputNumber =identity<number>(42);Powered by
Here is a generic class example:
classBox<T>{
content:T;constructor(content:T){this.content = content;}getContent():T{returnthis.content;}}let stringBox =newBox("Hello");let numberBox =newBox(123);Powered by
Best practices include:
Use descriptive names like <T>, <K, V>, or domain-specific names.
Avoid unnecessary complexity.
Use constraints (extends) to restrict acceptable types.
Generics improve code reusability by reducing duplication and enforcing consistent typing.
19. What are TypeScript utility types, and how are they used?
TypeScript provides built-in utility types to manipulate and transform existing types efficiently.
Here is an example:
interfaceTodo{
title:string;
description:string;
completed:boolean;}typePartialTodo= Partial<Todo>;// all properties optionaltypeRequiredTodo= Required<Todo>;// all properties requiredtypeTodoPreview= Pick<Todo,"title"|"completed">;// select specific propertiestypeTodoWithoutDescription= Omit<Todo,"description">;// exclude propertiesPowered by
These are especially useful when working with API responses, forms, or component props.
Reach for built-in utility types before writing your own mapped types; reviewers recognize them instantly.
20. What are conditional and mapped types in TypeScript?
Conditional types let you define logic within types based on relationships between them.
Here is an example:
typeIsString<T>=Textendsstring?"yes":"no";typeResult1= IsString<string>;// "yes"typeResult2= IsString<number>;// "no"Powered by
Mapped types allow you to transform all properties of a type at once.
Here is an example:
typeReadonlyTodo={readonly[Kinkeyof Todo]: Todo[K];};typeOptionalTodo={[Kinkeyof Todo]?: Todo[K];};Powered by
The key differences are:
Conditional types pick one of two types based on a condition (T extends U ? X : Y).
Mapped types loop over the keys of a type ([K in keyof T]) to transform every property at once.
21. What is the infer keyword used for in TypeScript?
infer lets you extract (infer) a type inside a conditional type.
Here is an example:
typeMyReturnType<T>=Textends(...args:any[])=>inferR?R:never;typeResult= MyReturnType<()=>number>;// numberPowered by
Often used in advanced utilities and generic type transformations.
22. What are template literal types?
Template literal types construct string types using interpolation.
Here is an example:
typeChangeEvent=`${string}Changed`;let e: ChangeEvent ="nameChanged";// OKPowered by
This is useful for:
Event naming
CSS class patterns
API route patterns
23. What are satisfies and as const in TypeScript?
satisfies checks that a value matches a type without changing the type TypeScript infers for it, so you keep the narrower literal types.
For example:
typeSettings={ mode:"light"|"dark"; version:number};const config ={
mode:"dark",
version:1} satisfies Settings;
config.mode;// type is "dark", not "light" | "dark"Powered by
With a type annotation (const config: Settings), config.mode would widen to "light" | "dark".
as const makes all properties read-only and literal.
For example:
const directions =["up","down"]asconst;// type is readonly ["up", "down"]Powered by
Both satisfies and as const are useful in React, config objects, and discriminated unions.
TypeScript Functions and Objects Interview Questions
In this section, we will explore TypeScript interview questions related to functions and objects.
24. How does function overloading work in TypeScript?
Function overloading allows you to define multiple function signatures for different argument types or patterns.
Here is an example:
functionadd(a:number, b:number):number;functionadd(a:string, b:string):string;functionadd(a:any, b:any):any{return a + b;}let sumNumbers =add(5,10);// 15let sumStrings =add("Hello, ","World");// "Hello, World"Powered by
Best practices include:
Declare all possible overloads before the implementation.
Use type guards to handle multiple types safely.
25. What are optional and rest parameters in TypeScript?
Optional and rest parameters make functions more flexible and expressive.
Here is an example:
functiongreet(name:string, age?:number){console.log(`Hello ${name}, age: ${age ??"unknown"}`);}functionsum(...numbers:number[]){return numbers.reduce((total, current)=> total + current,0);}Powered by
The key rules for using optional and rest parameters are:
Use ? for optional parameters.
Use ... for rest parameters (variadic arguments).
These are often tested in interviews to evaluate how well you handle dynamic function inputs.
26. What is the difference between readonly and const in TypeScript?
const applies to variables, while readonly applies to object properties.
Here is an example:
interfaceUser{readonly id:number;
name:string;}const user: User ={ id:1, name:"Bob"};// user.id = 2; // Error: Cannot assign to 'id'const{ id, name }= user;console.log(`User ${name} has ID ${id}`);Powered by
Some best practices for using readonly and const are:
Use readonly for objects that should not be changed, such as data returned from an API.
Use const for variables that should not be reassigned.
Combine destructuring with type annotations for cleaner, self-documenting code.
27. What is function type variance (covariance and contravariance)?
Function type variance describes how TypeScript decides if one function type can safely replace another, based on its parameter types and return types.
Return types: Covariant
A function is allowed to return a more specific type than what the caller expects. For example:
typeAnimal={ name:string};typeDog= Animal &{bark:()=>void};letf:()=> Animal;letg:()=>Dog=()=>({ name:"Rex",bark(){}});
f = g;// OK: Dog is a subtype of AnimalPowered by
Parameter types: Contravariant
A function is allowed to accept more general parameter types than expected. For example:
typeDog={ name:string;bark:()=>void};typeAnimal={ name:string};typeHandleDog=(dog: Dog)=>void;typeHandleAnimal=(animal: Animal)=>void;let handleDog:HandleDog= d =>console.log(d.bark());let handleAnimal:HandleAnimal= a =>console.log(a.name);// A function that accepts an Animal is more general,// so it can stand in for one that accepts a Dog
handleDog = handleAnimal;// OKPowered by
This check needs strictFunctionTypes, which strict turns on, and it only applies to function-type properties. Parameters of methods declared with method syntax (handle(dog: Dog): void) are still checked bivariantly, a classic senior-level follow-up.
28. What are this types in TypeScript?
this types let methods return the same type as the class, useful for fluent APIs:
classBuilder{setName(name:string):this{// ...returnthis;}}newBuilder().setName("Test");// chaining worksPowered by
TypeScript OOP Interview Questions
The following questions cover key TypeScript OOP concepts frequently discussed in technical interviews.
29. How does TypeScript support object-oriented programming (OOP)?
TypeScript supports OOP principles such as classes, inheritance, and access modifiers.
Classes define reusable blueprints for objects, and inheritance allows one class to extend another to share properties and behaviors.
Here is an example:
classAnimal{constructor(public name:string){}move(distance:number){console.log(`${this.name} moved ${distance}m.`);}}classDogextendsAnimal{bark(){console.log("Woof!");}}const dog =newDog("Buddy");
dog.bark();// Woof!
dog.move(10);// Buddy moved 10m.Powered by
Access modifiers (public, protected, and private) control which code can use a class’s members; question 31 compares them. The public name shorthand in the constructor is a parameter property, which Node.js type stripping and the erasableSyntaxOnly flag reject, so some teams now declare the field explicitly.
30. What is the difference between abstract classes and interfaces in TypeScript?
Both abstract classes and interfaces define contracts for objects or classes, but they serve different purposes.
Abstract classes can include shared implementation and abstract methods.
Interfaces only describe structure, not implementation.
Here is an example:
abstractclassShape{abstractgetArea():number;// must be implemented}classCircleextendsShape{constructor(public radius:number){super();}getArea():number{return Math.PI*this.radius **2;}}Powered by
Best practices include:
Use abstract classes when you need shared logic across related classes.
Use interfaces for flexible type contracts and decoupled code design.
31. What is the difference between private, protected, and public modifiers?
Here is a comparison of TypeScript’s access modifiers and what they control:
Modifier
Description
public
Accessible anywhere.
protected
Accessible within the class and its subclasses.
private
Accessible only inside the declaring class.
Using the correct access modifier keeps internal state from being changed from outside the class. These modifiers only exist at compile time; for privacy that holds at runtime, use JavaScript’s #field syntax.
32. What is the difference between implements and extends?
extends inherits behavior and properties, whereas implements enforces a contract but does not provide an implementation.
Here is an example:
interfaceLogger{log(msg:string):void;}classBase{foo(){}}classMyClassextendsBaseimplementsLogger{log(msg:string){}}Powered by
33. How do mixins work in TypeScript?
Mixins allow multiple reusable class components.
Here is an example:
typeConstructor<T={}>=new(...args:any[])=>T;functionTimestamped<TBase extends Constructor>(Base: TBase){returnclassextends Base {
timestamp = Date.now();};}classUser{}const TimestampedUser =Timestamped(User);Powered by
Useful when you need multiple inheritance patterns.
Practical TypeScript Interview Questions
These questions focus on real-world applications of TypeScript that often come up in interviews.
34. How would you migrate a JavaScript project to TypeScript?
Migrating a legacy JavaScript codebase to TypeScript should be incremental to minimize risk and disruption.
The recommended approach is:
Add a tsconfig.json with allowJs, and checkJs if you want JSDoc-typed JavaScript checked too.
Set "strict": false at first: since TypeScript 6.0, strict mode is on by default, and an untyped codebase will fail it.
Rename files from .js to .ts one module at a time, starting with shared utilities and types.
Use unknown (or any with a lint warning) as a temporary escape hatch, then replace it with proper types.
Turn the strict checks back on one at a time, usually noImplicitAny first and strictNullChecks next, until you can set "strict": true.
Example tsconfig.json for the first stage:
{"compilerOptions":{"allowJs":true,"checkJs":true,"strict":false,"rootDir":"./src","outDir":"./dist"},"include":["src"]}Powered by
Migrating in stages keeps the app shipping while type coverage grows.
35. How do you use TypeScript with React?
Using TypeScript in React improves type safety for props and state, which helps prevent runtime errors.
Here is an example:
interfaceHeaderProps{
title:string;
subtitle?:string;}functionHeader({ title, subtitle }: HeaderProps){return(<header><h1>{title}</h1>{subtitle &&<p>{subtitle}</p>}</header>);}Powered by
Typing props on the function parameter, rather than with React.FC, is now the common style: it reads like a plain function and works with generic components.
Defining prop types helps TypeScript catch missing or incorrectly typed props at compile time, which improves reliability and developer productivity.
36. How do you use TypeScript with Node.js?
TypeScript adds type safety to Node.js API routes, configuration, and middleware.
Typing Request and Response gives you autocompletion and compile errors for misspelled properties.
TypeScript makes Node.js APIs easier to maintain and refactor safely.
Node.js can also run .ts files directly through type stripping, so node server.ts works with no build step. Node removes the type annotations without checking them, so you still run tsc --noEmit in CI, and syntax that generates code (enums, namespaces with runtime code, and parameter properties) fails at startup. Setting erasableSyntaxOnly in tsconfig.json catches that syntax at compile time.
37. How do you handle third-party JavaScript libraries that lack TypeScript definitions?
Some libraries don’t include built-in types. In these cases, you have two main options:
Option 1: Install community-maintained types
npm install --save-dev @types/library-namePowered by
Option 2: Create a custom declaration file
// custom.d.tsdeclaremodule"legacy-library"{exportfunctioninit():void;}Powered by
Tips include:
Always check @types before writing custom declarations.
For a large library, declare only the functions you call and extend the file as you use more.
Proper typing of third-party libraries increases confidence and reduces runtime bugs.
TypeScript Configuration and Tooling Interview Questions
This section covers essential TypeScript configuration and tooling topics frequently discussed in technical interviews.
38. What is tsconfig.json, and why is it important?
The tsconfig.json file is the central configuration for any TypeScript project.
It defines compiler behavior, includes files, and enables features.
Here is an example:
{"compilerOptions":{"target":"es2025","module":"nodenext","rootDir":"./src","outDir":"./dist","types":["node"],"noUncheckedIndexedAccess":true,"noImplicitReturns":true,"noFallthroughCasesInSwitch":true},"include":["src"]}Powered by
Key settings include:
target: The JavaScript version to emit.
module: The module system; nodenext for Node.js, esnext or preserve when a bundler handles imports.
rootDir and outDir: Where the source lives and where the compiled files go.
types: Which @types packages load globally.
noUncheckedIndexedAccess: Types array[i] as possibly undefined, a check strict does not include.
TypeScript 6.0 changed several defaults, and TypeScript 7.0 kept them: strict is on, module defaults to esnext, rootDir defaults to the folder holding tsconfig.json, and types defaults to an empty list, so globals such as Node’s process disappear until you list "node". TypeScript 7.0 also turns old options into hard errors, including target: es5, moduleResolution: node, and baseUrl.
39. How do you configure TypeScript with build tools like Webpack, Vite, or Babel?
TypeScript works with every major build tool, but most bundlers only strip types and leave type checking to tsc.
Common setups include:
Webpack: ts-loader for on-the-fly compilation
Vite: built in, with no plugin; it transpiles .ts files but does not type-check, so run tsc --noEmit in your build script
Babel: @babel/preset-typescript for JS-heavy environments
Focus on real-world use cases rather than memorization.
Practice reading and understanding type errors, especially since TypeScript compiler messages are often part of technical assessments.
Practice projects:
Build small but complete apps to demonstrate practical skills:
React To-Do List with typed props and state.
Express REST API with typed request and response objects.
Utility libraries using generics and mapped types.
Common pitfalls:
Overusing any, which undermines TypeScript’s type safety.
Neglecting strict mode, which leads to runtime bugs.
Confusing null and undefined in type definitions.
Forgetting to install or configure type definitions for third-party libraries.
Communication tips:
During interviews, clearly explain your reasoning for type decisions.
Describe trade-offs between approaches (for instance: interface vs type alias or abstract class vs interface).
Show how TypeScript improves maintainability and scalability in projects.
Final Thoughts
TypeScript interviews reward the same skill as the job: modeling data precisely and knowing where types stop and runtime checks begin. If you can answer these 40 questions with your own examples and explain the trade-offs, you are ready for most front-end, full-stack, and Node.js rounds. For the general part of the interview, see our software engineer interview questions.
To keep learning, explore our full catalog of courses to continue expanding your knowledge across different technologies.
I’m Don—a Consultant, Developer, Engineer, Digital Architect, and Writer (basically, I wear a lot of hats 👨💻🎩). I love keeping digital platforms running smoothly and always finding ways to make them better. When I’m not coding, I’m writing about artificial intelligence, data science, and all things tech.
Over the years, I’ve worked on everything from building and optimizing software to deploying AI models and designing cloud solutions. I hold a Master of Science in Artificial Intelligence and a Bachelor of Science in Computer Science, both from Brunel University London.
FAQs
What is TypeScript used for?⌄
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Teams use it to build web front ends with React or Angular, Node.js back ends, and libraries, because static type checking catches errors before code runs and makes large codebases safer to refactor.
Why is TypeScript important for developers in 2026?⌄
Most React, Angular, and Node.js projects now start in TypeScript, so it is tested in most front-end and full-stack interviews. TypeScript 7.0, released in July 2026, made the compiler about ten times faster and kept strict mode on by default, which makes typed code the standard for new projects.
How can I practice TypeScript before interviews?⌄
Build small projects, such as a React to-do app with typed props or a Node.js API with typed requests, and turn on strict mode. Rewrite a few utility types like Partial or ReturnType yourself, and practice explaining compiler errors out loud in the TypeScript Playground.
What are common TypeScript interview mistakes to avoid?⌄
Common mistakes are reaching for any instead of unknown, using type assertions to silence errors, turning off strict mode, and confusing interfaces with type aliases. Interviewers also notice when candidates cannot explain why they chose a type, so describe the trade-off behind each decision, not just the syntax.
Do I need to know TypeScript 7 for a TypeScript interview?⌄
You rarely need TypeScript 7 internals, but you should know it is the Go-based compiler released in July 2026 and that it uses TypeScript 6.0 defaults: strict mode on, types set to an empty list, and old options such as baseUrl removed. Interviewers ask about this when a project upgrades.
Discover 21 Terraform interview questions and answers for 2026, from basic IaC concepts to advanced CI/CD integration, updated for Terraform 1.0+ best practices.
Master the technical interview process with these essential questions covering algorithms, system design, and behavioral scenarios. Get expert answers, code examples, and proven preparation strategies.
TypeScript interview questions test whether you can use static types to catch bugs before code runs: core types, the type system, generics, functions and classes, and the way you configure a real project. Below are the 40 questions I would prepare for, grouped from basic to advanced, each with a short answer and a code example you can compile.
In my work on web applications, I have seen strong typing cut bugs and make refactoring across teams safer. Most front-end and full-stack job postings I see now list TypeScript as a core requirement, and Microsoft, Google, Airbnb, and Netflix all use it in React, Angular, and Node.js codebases.
The answers reflect TypeScript 7.0, the Go-based compiler Microsoft released in July 2026, and the stricter defaults it kept from TypeScript 6.0.
Basic TypeScript Interview Questions
Basic TypeScript interview questions check that you know why TypeScript exists and how its core types behave.
1. Why use TypeScript over JavaScript?
TypeScript adds static typing and compile-time error checking, which helps developers detect bugs early and make codebases more predictable.
Types also document what each function expects, so large codebases stay easier to change.
2. What problems does TypeScript solve?
TypeScript addresses JavaScript’s weaknesses in type safety, scalability, and readability.
Enforcing clear type definitions prevents subtle runtime bugs and makes refactoring safer.
3. What are the main benefits of using static typing in TypeScript?
Static typing improves code reliability, auto-completion, and developer productivity.
It helps with early detection of type errors and allows IDEs to provide richer tooling support.
4. What are type annotations and why are they useful?
Type annotations allow developers to declare variable types explicitly.
This improves code readability and reduces runtime errors.
Here is an example:
In the above code, the compiler ensures that only the correct type can be assigned to each variable.
For example, if you try to assign a string to age, TypeScript will throw an error, which helps catch mistakes early.
Explicit typing is especially important for function parameters, return types, and API contracts, as it communicates expectations to other developers.
5. What is type inference in TypeScript?
TypeScript can automatically infer types based on assigned values.
This means you don’t always need to explicitly declare a type. TypeScript figures it out for you.
Here is an example:
In this example, TypeScript infers that count must be a number based on its initial value, so assigning a string later causes a compile-time error.
Best practices for type inference include:
6. How does TypeScript handle arrays, tuples, and enums?
TypeScript allows developers to enforce strict types on arrays, tuples, and enums to improve clarity and prevent runtime errors.
Here is a typed array example:
A typed array only accepts elements of its declared type.
Here is a tuple example:
Tuples define fixed-length arrays with specific types for each position.
They are useful for structured data where the order and type of elements matter.
Here is an enum example:
Enums provide named constants, improving readability and reducing invalid values.
They are especially useful for status codes, roles, and configuration options.
A common 2026 follow-up is whether you would still use an enum. Enums generate runtime code, so Node.js type stripping and the
erasableSyntaxOnlycompiler flag reject them. Many teams use anas constobject with a matching union type instead:7. What is the difference between any, unknown, and never types?
The following table highlights the key differences between the any, unknown, and never types in TypeScript.
Type
Description
any
Disables type checking entirely, allowing any value.
unknown
Safer alternative to any, you must check the type before using it.
never
Represents values that never occur (e.g., functions that always throw).
Here is an example:
A tip would be to prefer unknown over any to maintain type safety while retaining flexibility.
8. What is the difference between null and undefined in TypeScript?
The key differences between null and undefined are:
undefinedmeans a variable has been declared but not assigned a value.nullis an explicit value meaning no value.TypeScript's strictNullChecks mode treats them as separate types, which prevents accidental null-related bugs.
Here is an example:
9. What does the strict compiler option do?
The
strictflag turns on all of TypeScript’s strict type-checking rules. Since TypeScript 6.0, it is on by default, so a new project gets these checks unless you set"strict": false. The rules include:nullandundefinedout of other types unless you allow them, which prevents null reference errors.any, such as an untyped function parameter.bind,call, andapply.catchclause asunknowninstead ofany.Together, these checks catch null references and loose function types before they reach production.
TypeScript Type System Interview Questions
Let’s now look at some key TypeScript type system concepts commonly discussed in technical interviews.
10. What is the difference between interfaces and type aliases in TypeScript?
Both interfaces and type aliases describe the shape of objects, but they serve slightly different purposes.
Interfaces can be extended using extends, which makes them ideal for hierarchical object models.
Type aliases can represent unions, intersections, primitives, and more complex composite types.
Here is an example:
Use interfaces when defining object shapes or class contracts.
Use type aliases when you need flexible, composable types like unions or intersections.
11. What are union and intersection types in TypeScript?
Union types allow a variable to hold multiple possible types, while intersection types combine multiple types into one.
Here is a union example:
Here is an intersection example:
Union types are often used in function parameters.
Intersection types are common in complex object compositions.
12. What is type narrowing, and how do type guards work?
Type narrowing lets TypeScript infer a more specific type based on control flow.
Here is an example:
Type guards ensure safe runtime operations by verifying the type before performing specific actions.
You can use:
typeof: for primitivesinstanceof: for classesCustom type guards: functions that return a type predicate such as
pet is FishType guards improve type safety and reduce runtime errors.
13. What are literal types and discriminated unions in TypeScript?
Literal types restrict a variable to a specific set of predefined values.
Here is an example:
Discriminated unions combine literal types with object variants for pattern matching.
Here is an example:
Discriminated unions allow safe branching on object types and simplify logic in complex applications.
14. What are keyof, typeof, and in in TypeScript?
These operators let you build new types from existing types and values.
keyof: gets the property names of a typetypeof: gets the type of a valuein: used in mapped typesHere is an example:
15. What are index signatures in TypeScript?
Index signatures allow objects with dynamic keys.
Here is an example:
These are used for dictionaries, map-like objects, or dynamic configuration patterns.
16. What is structural typing in TypeScript?
Structural typing (duck typing) means types are compatible based on their structure, not their name.
Here is an example:
This makes TypeScript flexible and works well with JavaScript patterns.
17. What is declaration merging in TypeScript?
Declaration merging happens when TypeScript combines multiple declarations with the same name.
Here is an example merging two interfaces:
This is useful when extending third-party types or augmenting libraries.
Advanced TypeScript Interview Questions
Here are advanced TypeScript interview questions and answers.
18. What are generics in TypeScript, and why are they useful?
Generics allow you to write reusable, type-safe functions and classes that work with multiple data types.
Here is a generic function example:
Here is a generic class example:
Best practices include:
Use descriptive names like
<T>,<K, V>, or domain-specific names.Avoid unnecessary complexity.
Use constraints (extends) to restrict acceptable types.
Generics improve code reusability by reducing duplication and enforcing consistent typing.
19. What are TypeScript utility types, and how are they used?
TypeScript provides built-in utility types to manipulate and transform existing types efficiently.
Here is an example:
These are especially useful when working with API responses, forms, or component props.
Reach for built-in utility types before writing your own mapped types; reviewers recognize them instantly.
20. What are conditional and mapped types in TypeScript?
Conditional types let you define logic within types based on relationships between them.
Here is an example:
Mapped types allow you to transform all properties of a type at once.
Here is an example:
The key differences are:
T extends U ? X : Y).[K in keyof T]) to transform every property at once.21. What is the infer keyword used for in TypeScript?
inferlets you extract (infer) a type inside a conditional type.Here is an example:
Often used in advanced utilities and generic type transformations.
22. What are template literal types?
Template literal types construct string types using interpolation.
Here is an example:
This is useful for:
23. What are satisfies and as const in TypeScript?
satisfieschecks that a value matches a type without changing the type TypeScript infers for it, so you keep the narrower literal types.For example:
With a type annotation (
const config: Settings),config.modewould widen to"light" | "dark".as constmakes all properties read-only and literal.For example:
Both
satisfiesandas constare useful in React, config objects, and discriminated unions.TypeScript Functions and Objects Interview Questions
In this section, we will explore TypeScript interview questions related to functions and objects.
24. How does function overloading work in TypeScript?
Function overloading allows you to define multiple function signatures for different argument types or patterns.
Here is an example:
Best practices include:
25. What are optional and rest parameters in TypeScript?
Optional and rest parameters make functions more flexible and expressive.
Here is an example:
The key rules for using optional and rest parameters are:
Use
?for optional parameters.Use
...for rest parameters (variadic arguments).These are often tested in interviews to evaluate how well you handle dynamic function inputs.
26. What is the difference between readonly and const in TypeScript?
constapplies to variables, whilereadonlyapplies to object properties.Here is an example:
Some best practices for using
readonlyandconstare:27. What is function type variance (covariance and contravariance)?
Function type variance describes how TypeScript decides if one function type can safely replace another, based on its parameter types and return types.
Return types: Covariant
A function is allowed to return a more specific type than what the caller expects. For example:
Parameter types: Contravariant
A function is allowed to accept more general parameter types than expected. For example:
This check needs
strictFunctionTypes, whichstrictturns on, and it only applies to function-type properties. Parameters of methods declared with method syntax (handle(dog: Dog): void) are still checked bivariantly, a classic senior-level follow-up.28. What are this types in TypeScript?
thistypes let methods return the same type as the class, useful for fluent APIs:TypeScript OOP Interview Questions
The following questions cover key TypeScript OOP concepts frequently discussed in technical interviews.
29. How does TypeScript support object-oriented programming (OOP)?
TypeScript supports OOP principles such as classes, inheritance, and access modifiers.
Classes define reusable blueprints for objects, and inheritance allows one class to extend another to share properties and behaviors.
Here is an example:
Access modifiers (
public,protected, andprivate) control which code can use a class’s members; question 31 compares them. Thepublic nameshorthand in the constructor is a parameter property, which Node.js type stripping and theerasableSyntaxOnlyflag reject, so some teams now declare the field explicitly.30. What is the difference between abstract classes and interfaces in TypeScript?
Both abstract classes and interfaces define contracts for objects or classes, but they serve different purposes.
Abstract classes can include shared implementation and abstract methods.
Interfaces only describe structure, not implementation.
Here is an example:
Best practices include:
31. What is the difference between private, protected, and public modifiers?
Here is a comparison of TypeScript’s access modifiers and what they control:
Modifier
Description
public
Accessible anywhere.
protected
Accessible within the class and its subclasses.
private
Accessible only inside the declaring class.
Using the correct access modifier keeps internal state from being changed from outside the class. These modifiers only exist at compile time; for privacy that holds at runtime, use JavaScript’s
#fieldsyntax.32. What is the difference between implements and extends?
extendsinherits behavior and properties, whereasimplementsenforces a contract but does not provide an implementation.Here is an example:
33. How do mixins work in TypeScript?
Mixins allow multiple reusable class components.
Here is an example:
Useful when you need multiple inheritance patterns.
Practical TypeScript Interview Questions
These questions focus on real-world applications of TypeScript that often come up in interviews.
34. How would you migrate a JavaScript project to TypeScript?
Migrating a legacy JavaScript codebase to TypeScript should be incremental to minimize risk and disruption.
The recommended approach is:
allowJs, andcheckJsif you want JSDoc-typed JavaScript checked too."strict": falseat first: since TypeScript 6.0, strict mode is on by default, and an untyped codebase will fail it..jsto.tsone module at a time, starting with shared utilities and types.unknown(oranywith a lint warning) as a temporary escape hatch, then replace it with proper types.noImplicitAnyfirst andstrictNullChecksnext, until you can set"strict": true.Example tsconfig.json for the first stage:
Migrating in stages keeps the app shipping while type coverage grows.
35. How do you use TypeScript with React?
Using TypeScript in React improves type safety for props and state, which helps prevent runtime errors.
Here is an example:
Typing props on the function parameter, rather than with
React.FC, is now the common style: it reads like a plain function and works with generic components.Defining prop types helps TypeScript catch missing or incorrectly typed props at compile time, which improves reliability and developer productivity.
36. How do you use TypeScript with Node.js?
TypeScript adds type safety to Node.js API routes, configuration, and middleware.
Here is an example:
Typing
RequestandResponsegives you autocompletion and compile errors for misspelled properties.TypeScript makes Node.js APIs easier to maintain and refactor safely.
Node.js can also run
.tsfiles directly through type stripping, sonode server.tsworks with no build step. Node removes the type annotations without checking them, so you still runtsc --noEmitin CI, and syntax that generates code (enums, namespaces with runtime code, and parameter properties) fails at startup. SettingerasableSyntaxOnlyin tsconfig.json catches that syntax at compile time.37. How do you handle third-party JavaScript libraries that lack TypeScript definitions?
Some libraries don’t include built-in types. In these cases, you have two main options:
Option 1: Install community-maintained types
Option 2: Create a custom declaration file
Tips include:
Always check
@typesbefore writing custom declarations.For a large library, declare only the functions you call and extend the file as you use more.
Proper typing of third-party libraries increases confidence and reduces runtime bugs.
TypeScript Configuration and Tooling Interview Questions
This section covers essential TypeScript configuration and tooling topics frequently discussed in technical interviews.
38. What is tsconfig.json, and why is it important?
The tsconfig.json file is the central configuration for any TypeScript project.
It defines compiler behavior, includes files, and enables features.
Here is an example:
Key settings include:
target: The JavaScript version to emit.module: The module system;nodenextfor Node.js,esnextorpreservewhen a bundler handles imports.rootDirandoutDir: Where the source lives and where the compiled files go.types: Which@typespackages load globally.noUncheckedIndexedAccess: Typesarray[i]as possiblyundefined, a checkstrictdoes not include.TypeScript 6.0 changed several defaults, and TypeScript 7.0 kept them:
strictis on,moduledefaults toesnext,rootDirdefaults to the folder holding tsconfig.json, andtypesdefaults to an empty list, so globals such as Node’sprocessdisappear until you list"node". TypeScript 7.0 also turns old options into hard errors, includingtarget: es5,moduleResolution: node, andbaseUrl.39. How do you configure TypeScript with build tools like Webpack, Vite, or Babel?
TypeScript works with every major build tool, but most bundlers only strip types and leave type checking to
tsc.Common setups include:
Webpack:
ts-loaderfor on-the-fly compilationVite: built in, with no plugin; it transpiles
.tsfiles but does not type-check, so runtsc --noEmitin your build scriptBabel:
@babel/preset-typescriptfor JS-heavy environmentsExample Vite configuration:
Align compiler and bundler settings, enable incremental builds, and use source maps for easier debugging.
40. How do you configure ESLint with TypeScript for better code quality?
ESLint helps maintain consistent coding standards and catch errors early.
Install required packages:
Example
eslint.config.mjs, ESLint’s flat config format, which replaced.eslintrcfiles:Tips include:
Tips for Acing Your TypeScript Interview
Before your interview, you should focus on mastering both your technical skills and communication skills.
Here are some of the ways in which you can do so:
Study approach:
Practice projects:
Common pitfalls:
Communication tips:
Final Thoughts
TypeScript interviews reward the same skill as the job: modeling data precisely and knowing where types stop and runtime checks begin. If you can answer these 40 questions with your own examples and explain the trade-offs, you are ready for most front-end, full-stack, and Node.js rounds. For the general part of the interview, see our software engineer interview questions.
To keep learning, explore our full catalog of courses to continue expanding your knowledge across different technologies.