”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 技术面试问题 - 部分打字稿

技术面试问题 - 部分打字稿

发布于2024-11-06
浏览:343

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(element: T): T {
 return element;
}

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.

const stringData2 = returnGenericElement("Hello world");


const numberData2 = returnGenericElement(5);

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:

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

Then,

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

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.

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

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:

const operation = new Addition();


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


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

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

function returnGenericElement(element: T): T {
 return element;
}

to

function returnGenericElement(element) {
 return element;
}

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.

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


interface CatInterface {
 color: string;
}


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

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

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)
};

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.

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


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

Union type:

type animal = cat | dog;

Intersection type:

type intersectionAnimal = cat & dog;

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.

class pet implements animal{
   name: string;
   age: number;
   breed: string;
   constructor(name: string, age: number, breed: string){
       this.name = name;
       this.age = age;
       this.breed = breed;
   }
}

Technical Interview Questions - Part  Typescript

Typescript allows us to use “implements” with:

a. Intersection types

class pet2 implements intersectionAnimal {
 name: string;
 age: number;
 color: string;
 breed: string;
 constructor(name: string, age: number, color: string, breed: string) {
   this.name = name;
   this.age = age;
   this.color = color;
   this.breed = breed;
 }
}

b. Interfaces

interface CatInterface {
 name: string;
 age: number;
 color: string;
}
class pet3 implements CatInterface {
 name: string;
 age: number;
 color: string;
 constructor(name: string, age: number, color: string) {
   this.name = name;
   this.age = age;
   this.color = color;
 }
}

c. Single Type.

class pet4 implements cat {
 name: string;
 age: number;
 color: string;
 constructor(name: string, age: number, color: string) {
   this.name = name;
   this.age = age;
   this.color = color;
 }
}

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

interface petUnionType extends animal {
 name: string;
 age: number;
 breed: string;
}

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.

interface petIntersectionType extends intersectionAnimal {
 name: string;
 age: number;
 color: string;
 breed: string;
}


interface petCatInterface extends CatInterface {
 name: string;
 age: number;
 color: string;
}

Also, you can extend a single type.

interface petCatType extends cat {
   name: string;
   age: number;
   color: string;
   }

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.

let anyVariable: any;

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

anyVariable.trim();
anyVariable.length;

You can assign any value to an any variable:

anyVariable = 5;
anyVariable = "Hello";

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

let booleanVariable: boolean = anyVariable;
let numberVariable: number = anyVariable;

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.

let unknownVariable: unknown;

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

unknownVariable.trim();
unknownVariable.length;

Technical Interview Questions - Part  Typescript

Before using it, we should perform checks like:

if (typeof unknownVariable === "string") {
 unknownVariable.trim();
}

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

unknownVariable = 5;
unknownVariable = "Hello";

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

let booleanVariable2: boolean = unknownVariable;
let numberVariable2: number = unknownVariable;

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.

let nullVariable: null;

nullVariable = null;

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

nullVariable = "Hello";

Technical Interview Questions - Part  Typescript


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

function throwError(message: string): never {
 throw new Error(message);
}


function infiniteLoop(): never {
 while (true) {
   console.log("Hello");
 }
}

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 ?

版本声明 本文转载于:https://dev.to/giulianaolmos/technical-interview-questions-part-2-typescript-1njn?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 在 Go 中使用 WebSocket 进行实时通信
    在 Go 中使用 WebSocket 进行实时通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    编程 发布于2024-11-06
  • 如何在 Python 中使用代理运行 Selenium Webdriver?
    如何在 Python 中使用代理运行 Selenium Webdriver?
    使用 Python 中的代理运行 Selenium Webdriver当您尝试将 Selenium Webdriver 脚本导出为 Python 脚本并从命令行执行时,可能会遇到在使用代理的情况下出现错误。本文旨在解决此问题,提供一种使用代理有效运行脚本的解决方案。代理集成要使用代理运行 Selen...
    编程 发布于2024-11-06
  • || 什么时候运算符充当 JavaScript 中的默认运算符?
    || 什么时候运算符充当 JavaScript 中的默认运算符?
    理解 || 的目的JavaScript 中非布尔操作数的运算符在 JavaScript 中,||运算符通常称为逻辑 OR 运算符,通常用于计算布尔表达式。但是,您可能会遇到 || 的情况。运算符与非布尔值一起使用。在这种情况下,||运算符的行为类似于“默认”运算符。它不返回布尔值,而是根据某些规则返...
    编程 发布于2024-11-06
  • 探索 Java 23 的新特性
    探索 Java 23 的新特性
    亲爱的开发者、编程爱好者和学习者, Java 开发工具包 (JDK) 23 已正式发布(2024/09/17 正式发布),标志着 Java 编程语言发展的又一个重要里程碑。此最新更新引入了大量令人兴奋的功能和增强功能,旨在改善开发人员体验、性能和模块化。 在本文中,我将分享 JDK 23 的一些主要...
    编程 发布于2024-11-06
  • ES6 数组解构:为什么它没有按预期工作?
    ES6 数组解构:为什么它没有按预期工作?
    ES6 数组解构:不可预见的行为在 ES6 中,数组的解构赋值可能会导致意外的结果,让程序员感到困惑。下面的代码说明了一个这样的实例:let a, b, c [a, b] = ['A', 'B'] [b, c] = ['BB', 'C'] console.log(`a=${a} b=${b} c=$...
    编程 发布于2024-11-06
  • 如何调整图像大小以适合浏览器窗口而不变形?
    如何调整图像大小以适合浏览器窗口而不变形?
    调整图像大小以适应浏览器窗口而不失真调整图像大小以适应浏览器窗口是一项看似简单的解决方案的常见任务。然而,遵守特定要求(例如保留比例和避免裁剪)可能会带来挑战。没有滚动条和 Javascript 的解决方案(仅限 CSS)<html> <head> <style&g...
    编程 发布于2024-11-06
  • 面向对象 - Java 中的方法
    面向对象 - Java 中的方法
    在Java中的面向对象编程中,方法在定义类和对象的行为中起着至关重要的作用。它们允许您执行操作、操纵数据以及与其他对象交互。它们允许您执行操作、操纵数据以及与其他对象交互。在本文中,我们将探讨 Java 中的方法、它们的特性以及如何有效地使用它们。 什么是方法? 方法是类中定义对象行...
    编程 发布于2024-11-06
  • 如何使用 MAMP 修复 Mac 上 Laravel 迁移中的“没有这样的文件或目录”错误?
    如何使用 MAMP 修复 Mac 上 Laravel 迁移中的“没有这样的文件或目录”错误?
    解决 Mac 上 Laravel 迁移中的“没有这样的文件或目录”错误简介:当尝试在 Mac 上的 Laravel 项目中运行“php artisan migrate”命令时,用户经常会遇到找不到文件或目录的错误。这个令人沮丧的问题可能会阻碍迁移过程并阻止开发人员在项目中取得进展。在本文中,我们将深...
    编程 发布于2024-11-06
  • SOLID 原则使用一些有趣的类比与车辆示例
    SOLID 原则使用一些有趣的类比与车辆示例
    SOLID 是计算机编程中五个良好原则(规则)的缩写。 SOLID 允许程序员编写更易于理解和稍后更改的代码。 SOLID 通常与使用面向对象设计的系统一起使用。 让我们使用车辆示例来解释 SOLID 原理。想象一下,我们正在设计一个系统来管理不同类型的车辆,例如汽车和电动汽车,...
    编程 发布于2024-11-06
  • 如何从另一个异步函数中的异步函数返回解析值?
    如何从另一个异步函数中的异步函数返回解析值?
    如何从异步函数返回一个值?在提供的代码中,init()方法返回一个Promise,但是getPostById() 方法尝试直接访问 Promise 返回的值。为了解决这个问题,需要修改 init() 方法,使其在 Promise 解析后返回 getPostById() 的值。更新后的代码如下:cla...
    编程 发布于2024-11-06
  • 了解如何使用 React 构建多人国际象棋游戏
    了解如何使用 React 构建多人国际象棋游戏
    Hello and welcome! ?? Today I bring a tutorial to guide you through building a multiplayer chess game using SuperViz. Multiplayer games require real-t...
    编程 发布于2024-11-06
  • 如何使用 JavaScript 正则表达式验证 DD/MM/YYYY 格式的日期?
    如何使用 JavaScript 正则表达式验证 DD/MM/YYYY 格式的日期?
    使用 JavaScript 正则表达式验证 DD/MM/YYYY 格式的日期验证日期是编程中的常见任务,并且能够确保日期采用特定格式至关重要。在 JavaScript 中,正则表达式提供了执行此类验证的强大工具。考虑用于验证 YYYY-MM-DD 格式日期的正则表达式模式:/^\d{4}[\/\-]...
    编程 发布于2024-11-06
  • JavaScript 中的节流和去抖:初学者指南
    JavaScript 中的节流和去抖:初学者指南
    使用 JavaScript 时,过多的事件触发器可能会降低应用程序的速度。例如,用户调整浏览器窗口大小或在搜索栏中输入内容可能会导致事件在短时间内重复触发,从而影响应用程序性能。 这就是节流和去抖可以发挥作用的地方。它们可以帮助您管理在处理过于频繁触发的事件时调用函数的频率。 ?什么...
    编程 发布于2024-11-06
  • 在 Go 中导入私有 Bitbucket 存储库时如何解决 403 Forbidden 错误?
    在 Go 中导入私有 Bitbucket 存储库时如何解决 403 Forbidden 错误?
    Go 从私有 Bitbucket 存储库导入问题排查(403 禁止)使用 go get 命令从 Bitbucket.org 导入私有存储库可能会遇到 403 Forbidden 错误。要解决此问题,请按照以下步骤操作:1.建立 SSH 连接:确保您已设置 SSH 密钥并且能够使用 SSH 连接到 B...
    编程 发布于2024-11-06
  • Singleton 和原型 Spring Bean 范围:详细探索
    Singleton 和原型 Spring Bean 范围:详细探索
    当我第一次开始使用 Spring 时,最让我感兴趣的概念之一是 bean 范围的想法。 Spring 提供了各种 bean 作用域,用于确定在 Spring 容器内创建的 bean 的生命周期。最常用的两个范围是 Singleton 和 Prototype。了解这些范围对于设计高效且有效的 Spri...
    编程 发布于2024-11-06

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3