search
HomeWeb Front-endJS TutorialTypeScript Interview Questions

TypeScript Interview Questions

Question - What is TypeScript?

  • TypeScript is a superset of Javascript
  • Adds static types, allowing for improved code quality and error checking before runtime.
  • It supports features like interfaces, enums, generics, and more.
  • Provides better error checking, enhanced tools, and improved code readability.

Question - What is explicit and implicit type assignment?

  • Explicit means writing out the type. Like below -
let firstName: string = "Rutvik";
  • Implicit means TypeScript will guess the type, based on the value. The below type will be considered a number
let age = 23;

Question - Difference between any, unknown and never in TypeScript?

  • The type of any is used to assign any type of a variable.
  • It will not give error even if you reassign another type.
let x: any = 10;
x = 'hello'; // No TypeScript error
console.log(x.toUpperCase()); // No TypeScript error
  • The type unknown is better than type any, because it requires us checking the type before performing operations on value.
let y: unknown = 10;
// Type assertion needed before using y as number
if (typeof y === 'number') {
    console.log(y.toFixed(2));
}
  • The type never represents value that never occurs.
  • It is typically used for return statements of function that doesn’t returns properly.
function throwError(message: string): never {
    throw new Error(message);
}

Question - How do you give the type of Arrays?

  • For typing array, we need to give the type as below. In this below example the array can contain type of string only.
const names: string[] = ["Rutvik", "Rohit", "Virat"];
names.push("Bumrah"); // no error
  • We can also use a readonly keyword, which prevents the array been changed.
const names: readonly string[] = ["Rutvik", "Rohit", "Virat"];
names.push("Bumrah"); // Error: Property 'push' does not exist on type 'readonly string[]'.

Question - What is Type Inference in array?

  • If we don’t give any type to an array, it will infer the type automatically.
const numbers = [1, 2, 3]; // inferred to type number[]
numbers.push(4); // no error

Question - What are tuples?

  • It is a type array with pre-defined length and types.
  • It is very useful in giving types of mixed array with different types.
let ourTuple: [number, boolean, string];

// initialize correctly
ourTuple = [5, false, 'Coding Hero was here'];

Question - What are readonly tuples?

  • If we don’t make a tuple readonly, we can add more items to the one defined and TypeScript will not throw any error.
let ourTuple: [number, boolean, string];

// initialize correctly
ourTuple = [5, false, 'Coding Hero was here'];
//No safety in indexes from 3
ourTuple.push('This is wrong');
  • Now, to fix it we use the keyword readonly before the type.
let ourTuple: readonly [number, boolean, string];
// initialize correctly
ourTuple = [5, false, 'Coding Hero was here'];
// throws error as it is readonly
ourTuple.push('Coding Hero took a day off');

Question - How to give the types for Objects?

  • We can give the type of object by creating another object like structure and specifying the keys and the type of the keys in the object.
interface CarTypes {
    brand: string,
    model: string,
    year: number
}


const car: CarTypes = {
  brand: "Tata",
  model: "Punch",
  year: 2020
};

Question - How to have optional properties in Objects?

  • To give an optional property or key, we need to add the ? after thet key.
let firstName: string = "Rutvik";

Question - Explain enum in TypeScript?

  • An enum is a type of variables which are constants. You have to use the values within it only.
  • The values are numeric by default and starts with 0 and increments by 1.
  • They can be numeric or string-based
let age = 23;
let x: any = 10;
x = 'hello'; // No TypeScript error
console.log(x.toUpperCase()); // No TypeScript error

Question - What are Type Aliases?

  • They allow to define type with a custom name and can be used for all primitive types like string and number and also complex type like objects and arrays.
let y: unknown = 10;
// Type assertion needed before using y as number
if (typeof y === 'number') {
    console.log(y.toFixed(2));
}

Question - What are interfaces?

  • Interfaces are like type but can be used only for objects.
function throwError(message: string): never {
    throw new Error(message);
}

Question - How to extend interfaces?

  • Interfaces can be extended with the extend keyword.
const names: string[] = ["Rutvik", "Rohit", "Virat"];
names.push("Bumrah"); // no error

Question - What are Union and Intersection types?

Union :-

  • Union types are used when the property can be more then one value, like string or number.
  • For this reason they are also called OR and are used by using | symbol.
const names: readonly string[] = ["Rutvik", "Rohit", "Virat"];
names.push("Bumrah"); // Error: Property 'push' does not exist on type 'readonly string[]'.

Intersection :-

  • Intersesction types are used when combines multiple types into one.
  • For this reason they are also called AND and are used by using & symbol.
const numbers = [1, 2, 3]; // inferred to type number[]
numbers.push(4); // no error

Question - What are functions in Typescript ?

How to give the return type in function?

  • We can give the return types of functions with : symbol after function name.
let ourTuple: [number, boolean, string];

// initialize correctly
ourTuple = [5, false, 'Coding Hero was here'];

How to give type of parameters in function?

  • We can give the type of parameters by mentioning them after each parameter with : symbol.
let ourTuple: [number, boolean, string];

// initialize correctly
ourTuple = [5, false, 'Coding Hero was here'];
//No safety in indexes from 3
ourTuple.push('This is wrong');

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

  • With default parameter, we can mark a parameter as optional. Like this, where c is optional and denoted by ?.
let ourTuple: readonly [number, boolean, string];
// initialize correctly
ourTuple = [5, false, 'Coding Hero was here'];
// throws error as it is readonly
ourTuple.push('Coding Hero took a day off');
  • The default values(an ES6 feature), goes after the type.
interface CarTypes {
    brand: string,
    model: string,
    year: number
}


const car: CarTypes = {
  brand: "Tata",
  model: "Punch",
  year: 2020
};
  • The rest parameters(an ES6 feature), are given the type of array, because they convert passed items in array.
interface CarTypes {
    brand: string,
    model: string,
    year?: number
}

const car: CarTypes = {
  brand: "Tata",
  model: "Punch"
};

Question - What is casting in TypeScript?

  • Casting is the process of overriding a type of a variable.
  • Like in the below example, the type is unknown but is made string while using with the as keyword.
enum Direction {
  Up = 1,
  Down,
  Left,
  Right,
}
console.log(Direction.Up); // 1
console.log(Direction.Down); // 2
  • We can also use in place of as. Both means the same.
let firstName: string = "Rutvik";

Question - What are Generics in TypeScript ?

  • Generics in Typeascript allow you to create reusable components or dunctions that can work with multiple data types.
let age = 23;

Question - Utility Types in Typescript?

  • TypeScript provides Utility Types to simplify common type transformations.
  • These types make it easier to manipulate and interact with object and interface types.
  • Here’s a breakdown of some commonly used utility types:

1. Partial

  • Makes all properties of type T optional.
  • Use case: When you want to create an object where only some properties are required.
let x: any = 10;
x = 'hello'; // No TypeScript error
console.log(x.toUpperCase()); // No TypeScript error

2. Required

  • Makes all properties of type T required.
  • Use case: When you want to enforce that all properties must be present.
let y: unknown = 10;
// Type assertion needed before using y as number
if (typeof y === 'number') {
    console.log(y.toFixed(2));
}

3. Readonly

  • Makes all properties of type T read-only.
  • Use case: To ensure that an object’s properties cannot be modified.
function throwError(message: string): never {
    throw new Error(message);
}

4. Pick

  • Creates a type by picking a set of properties K from type T.
  • Use case: When you need only specific properties from a type.
const names: string[] = ["Rutvik", "Rohit", "Virat"];
names.push("Bumrah"); // no error

5. Omit

  • Creates a type by omitting a set of properties K from type T.
  • Use case: When you want all properties except specific ones.
const names: readonly string[] = ["Rutvik", "Rohit", "Virat"];
names.push("Bumrah"); // Error: Property 'push' does not exist on type 'readonly string[]'.

6. Record

  • Constructs a type with keys K and values of type T.
  • Use case: To create an object type with fixed keys and consistent value types.
const numbers = [1, 2, 3]; // inferred to type number[]
numbers.push(4); // no error

7. Exclude

  • Excludes from type T all types that are assignable to U.
  • Use case: To filter out specific types.
let ourTuple: [number, boolean, string];

// initialize correctly
ourTuple = [5, false, 'Coding Hero was here'];

8. Extract

  • Extracts from type T only types that are assignable to U.
  • Use case: To narrow down types to a specific subset.
let ourTuple: [number, boolean, string];

// initialize correctly
ourTuple = [5, false, 'Coding Hero was here'];
//No safety in indexes from 3
ourTuple.push('This is wrong');

9. NonNullable

  • Excludes null and undefined from type T.
  • Use case: To ensure a value is neither null nor undefined.
let ourTuple: readonly [number, boolean, string];
// initialize correctly
ourTuple = [5, false, 'Coding Hero was here'];
// throws error as it is readonly
ourTuple.push('Coding Hero took a day off');

10. ReturnType

  • Infers the return type of a function type.
  • Use case: To capture and use the return type of a function.
interface CarTypes {
    brand: string,
    model: string,
    year: number
}


const car: CarTypes = {
  brand: "Tata",
  model: "Punch",
  year: 2020
};

11. InstanceType

  • Constructs a type consisting of the instance type of a constructor function type T.
  • Use case: To get the type of a class instance.
interface CarTypes {
    brand: string,
    model: string,
    year?: number
}

const car: CarTypes = {
  brand: "Tata",
  model: "Punch"
};

12. Parameters

  • Extracts the types of parameters of a function type.
  • Use case: To reuse the parameter types of a function.
enum Direction {
  Up = 1,
  Down,
  Left,
  Right,
}
console.log(Direction.Up); // 1
console.log(Direction.Down); // 2

The above is the detailed content of TypeScript Interview Questions. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use