search
HomeWeb Front-endJS TutorialTechnical Interview Questions - Part Typescript

Introduction

Hello, hello!! :D

Hope you’re all doing well!

How we’re really feeling:
Technical Interview Questions - Part  Typescript

I’m back with the second part of this series. ?

In this chapter, we’ll dive into the ✨Typescript✨ questions I’ve faced during interviews.

I’ll keep the intro short, so let’s jump right in!

## Questions
1. What are generics in typescript? What is ?
2. What are the differences between interfaces and types?
3. What are the differences between any, null, unknown, and never?


Question 1: What are generics in typescript? What is ?

The short answer is...

Generics in TypeScript allow us to create reusable functions, classes, and interfaces that can work with a variety of types, without having to specify a particular one. This helps to avoid using any as a catch-all type.

The syntax is used to declare a generic type, but you could also use , , or any other placeholder.

How does it work?

Let’s break it down with an example.

Suppose I have a function that accepts a parameter and returns an element of the same type. If I write that function with a specific type, it would look like this:

function returnElement(element: string): string {
 return element;
}


const stringData = returnElement("Hello world");

I know the type of stringData will be “string” because I declared it.

Technical Interview Questions - Part  Typescript

But what happens if I want to return a different type?

const numberData = returnElement(5);

I will receive an error message because the type differs from what was declared.

Technical Interview Questions - Part  Typescript

The solution could be to create a new function to return a number type.

function returnNumber(element: number): number {
 return element;
}

That approach would work, but it could lead to duplicated code.

A common mistake to avoid this is using any instead of a declared type, but that defeats the purpose of type safety.

function returnElement2(element: any): any {
 return element;
}

However, using any causes us to lose the type safety and error detection feature that Typescript has.
Also, if you start using any whenever you need to avoid duplicate code, your code will lose maintainability.

This is precisely when it’s beneficial to use generics.

function returnGenericElement<t>(element: T): T {
 return element;
}
</t>

The function will receive an element of a specific type; that type will replace the generic and remain so throughout the runtime.

This approach enables us to eliminate duplicated code while preserving type safety.

function returnElement(element: string): string {
 return element;
}


const stringData = returnElement("Hello world");

But what if I need a specific function that comes from an array?

We could declare the generic as an array and write it like this:

const numberData = returnElement(5);

Then,

function returnNumber(element: number): number {
 return element;
}

The declared types will be replaced by the type provided as a parameter.

Technical Interview Questions - Part  Typescript

We can also use generics in classes.

function returnElement2(element: any): any {
 return element;
}

I have three points to make about this code:

  1. add is an anonymous arrow function (which I discussed in the first chapter).
  2. The generic can be named , , or even , if you prefer.
  3. Since we haven't specified the type yet, we can't implement operations inside the classes. Therefore, we need to instantiate the class by declaring the type of the generic and then implement the function.

Here’s how it looks:

function returnGenericElement<t>(element: T): T {
 return element;
}
</t>

And, one last thing to add before ending this question.
Remember that generics are a feature of Typescript. That means the generics will be erased when we compile it into Javascript.

From

const stringData2 = returnGenericElement("Hello world");


const numberData2 = returnGenericElement(5);

to

function returnLength<t>(element: T[]): number {
 return element.length;
}
</t>

Question 2: What are the differences between interfaces and types?

The short answer is:

  1. Declaration merging works with interfaces but not with types.
  2. You cannot use implements in a class with union types.
  3. You cannot use extends with an interface using union types.

Regarding the first point, what do I mean by declaration merging?

Let me show you:
I’ve defined the same interface twice while using it in a class. The class will then incorporate the properties declared in both definitions.

const stringLength = returnLength(["Hello", "world"]);

This does not occur with types. If we attempt to define a type more than once, TypeScript will throw an error.

class Addition<u> {
 add: (x: U, y: U) => U;
}
</u>

Technical Interview Questions - Part  Typescript

Technical Interview Questions - Part  Typescript

Regarding the following points, let’s differentiate between union and intersection types:

Union types allow us to specify that a value can be one of several types. This is useful when a variable can hold multiple types.

Intersection types allow us to combine types into one. It is defined using the & operator.

const operation = new Addition<number>();


operation.add = (x, y) => x + y; => We implement the function here


console.log(operation.add(5, 6)); // 11
</number>

Union type:

function returnGenericElement<t>(element: T): T {
 return element;
}
</t>

Intersection type:

function returnElement(element: string): string {
 return element;
}


const stringData = returnElement("Hello world");

If we attempt to use the implements keyword with a union type, such as Animal, TypeScript will throw an error. This is because implements expects a single interface or type, rather than a union type.

const numberData = returnElement(5);

Technical Interview Questions - Part  Typescript

Typescript allows us to use “implements” with:

a. Intersection types

function returnNumber(element: number): number {
 return element;
}

b. Interfaces

function returnElement2(element: any): any {
 return element;
}
function returnGenericElement<t>(element: T): T {
 return element;
}
</t>

c. Single Type.

const stringData2 = returnGenericElement("Hello world");


const numberData2 = returnGenericElement(5);

The same issue occurs when we try to use extends with a union type. TypeScript will throw an error because an interface cannot extend a union type. Here’s an example

function returnLength<t>(element: T[]): number {
 return element.length;
}
</t>

You cannot extend a union type because it represents multiple possible types, and it's unclear which type's properties should be inherited.

Technical Interview Questions - Part  Typescript

BUT you can extend a type or an interface.

const stringLength = returnLength(["Hello", "world"]);

Also, you can extend a single type.

class Addition<u> {
 add: (x: U, y: U) => U;
}
</u>

Question 3: What are the differences between any, null, unknown, and never?

Short answer:

Any => It’s a top-type variable (also called universal type or universal supertype). When we use any in a variable, the variable could hold any type. It's typically used when the specific type of a variable is unknown or expected to change. However, using any is not considered a best practice; it’s recommended to use generics instead.

const operation = new Addition<number>();


operation.add = (x, y) => x + y; => We implement the function here


console.log(operation.add(5, 6)); // 11
</number>

While any allows for operations like calling methods, the TypeScript compiler won’t catch errors at this stage. For instance:

function returnGenericElement<t>(element: T): T {
 return element;
}
</t>

You can assign any value to an any variable:

function returnGenericElement(element) {
 return element;
}

Furthermore, you can assign an any variable to another variable with a defined type:

interface CatInterface {
 name: string;
 age: number;
}


interface CatInterface {
 color: string;
}


const cat: CatInterface = {
 name: "Tom",
 age: 5,
 color: "Black",
};

Unknown => This type, like any, could hold any value and is also considered the top type. We use it when we don’t know the variable type, but it will be assigned later and remain the same during the runtime. Unknow is a less permissive type than any.

type dog = {
 name: string;
 age: number;
};


type dog = { // Duplicate identifier 'dog'.ts(2300)
 color: string;
};


const dog1: dog = {
 name: "Tom",
 age: 5,
 color: "Black", //Object literal may only specify known properties, and 'color' does not exist in type 'dog'.ts(2353)
};

Directly calling methods on unknown will result in a compile-time error:

type cat = {
 name: string;
 age: number;
};


type dog = {
 name: string;
 age: number;
 breed: string;
};

Technical Interview Questions - Part  Typescript

Before using it, we should perform checks like:

type animal = cat | dog;

Like any, we could assign any type to the variable.

type intersectionAnimal = cat & dog;

However, we cannot assign the unknown type to another type, but any or unknown.

function returnElement(element: string): string {
 return element;
}


const stringData = returnElement("Hello world");

This will show us an error
Technical Interview Questions - Part  Typescript


Null => The variable can hold either type. It means that the variable does not have a value.

const numberData = returnElement(5);

Attempting to assign any other type to a null variable will result in an error:

function returnNumber(element: number): number {
 return element;
}

Technical Interview Questions - Part  Typescript


Never => We use this type to specify that a function doesn’t have a return value.

function returnElement2(element: any): any {
 return element;
}

The end...

We finish with Typescript,

Technical Interview Questions - Part  Typescript

For today (?

I hope this was helpful to someone.

If you have any technical interview questions you'd like me to explain, feel free to let me know in the comments. ??

Have a great week ?

The above is the detailed content of Technical Interview Questions - Part Typescript. 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
Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment