Home Web Front-end JS Tutorial Technical Interview Questions - Part Typescript

Technical Interview Questions - Part Typescript

Oct 25, 2024 am 03:20 AM

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");
Copy after login
Copy after login
Copy after login
Copy after login

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);
Copy after login
Copy after login
Copy after login
Copy after login

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;
}
Copy after login
Copy after login
Copy after login
Copy after login

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;
}
Copy after login
Copy after login
Copy after login
Copy after login

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;
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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");
Copy after login
Copy after login
Copy after login
Copy after login

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);
Copy after login
Copy after login
Copy after login
Copy after login

Then,

function returnNumber(element: number): number {
 return element;
}
Copy after login
Copy after login
Copy after login
Copy after login

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;
}
Copy after login
Copy after login
Copy after login
Copy after login

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;
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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);
Copy after login
Copy after login

to

function returnLength<T>(element: T[]): number {
 return element.length;
}
Copy after login
Copy after login

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"]);
Copy after login
Copy after login

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;
}
Copy after login
Copy after login

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
Copy after login
Copy after login

Union type:

function returnGenericElement<T>(element: T): T {
 return element;
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Intersection type:

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


const stringData = returnElement("Hello world");
Copy after login
Copy after login
Copy after login
Copy after login

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);
Copy after login
Copy after login
Copy after login
Copy after login

Technical Interview Questions - Part  Typescript

Typescript allows us to use “implements” with:

a. Intersection types

function returnNumber(element: number): number {
 return element;
}
Copy after login
Copy after login
Copy after login
Copy after login

b. Interfaces

function returnElement2(element: any): any {
 return element;
}
Copy after login
Copy after login
Copy after login
Copy after login
function returnGenericElement<T>(element: T): T {
 return element;
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

c. Single Type.

const stringData2 = returnGenericElement("Hello world");


const numberData2 = returnGenericElement(5);
Copy after login
Copy after login

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;
}
Copy after login
Copy after login

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"]);
Copy after login
Copy after login

Also, you can extend a single type.

class Addition<U> {
 add: (x: U, y: U) => U;
}
Copy after login
Copy after login

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
Copy after login
Copy after login

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;
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

You can assign any value to an any variable:

function returnGenericElement(element) {
 return element;
}
Copy after login

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",
};
Copy after login

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)
};
Copy after login

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;
};
Copy after login

Technical Interview Questions - Part  Typescript

Before using it, we should perform checks like:

type animal = cat | dog;
Copy after login

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

type intersectionAnimal = cat & dog;
Copy after login

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");
Copy after login
Copy after login
Copy after login
Copy after login

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);
Copy after login
Copy after login
Copy after login
Copy after login

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

function returnNumber(element: number): number {
 return element;
}
Copy after login
Copy after login
Copy after login
Copy after login

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;
}
Copy after login
Copy after login
Copy after login
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 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.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles