」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 技術面試問題 - 部分打字稿

技術面試問題 - 部分打字稿

發佈於2024-11-06
瀏覽:267

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]刪除
最新教學 更多>
  • 如何使用Python有效地以相反順序讀取大型文件?
    如何使用Python有效地以相反順序讀取大型文件?
    在python 中,如果您使用一個大文件,並且需要從最後一行讀取其內容,則在第一行到第一行,Python的內置功能可能不合適。這是解決此任務的有效解決方案:反向行讀取器生成器 == ord('\ n'): 緩衝區=緩衝區[:-1] ...
    程式設計 發佈於2025-04-05
  • 如何將PANDAS DataFrame列轉換為DateTime格式並按日期過濾?
    如何將PANDAS DataFrame列轉換為DateTime格式並按日期過濾?
    將pandas dataframe列轉換為dateTime格式示例:使用column(mycol)包含以下格式的以下dataframe,以自定義格式:})指定的格式參數匹配給定的字符串格式。轉換後,MyCol列現在將包含DateTime對象。 date date filtering > = ...
    程式設計 發佈於2025-04-05
  • 如何使用FormData()處理多個文件上傳?
    如何使用FormData()處理多個文件上傳?
    )處理多個文件輸入時,通常需要處理多個文件上傳時,通常是必要的。 The fd.append("fileToUpload[]", files[x]); method can be used for this purpose, allowing you to send multi...
    程式設計 發佈於2025-04-05
  • 如何從Python中的字符串中刪除表情符號:固定常見錯誤的初學者指南?
    如何從Python中的字符串中刪除表情符號:固定常見錯誤的初學者指南?
    從python import codecs import codecs import codecs 導入 text = codecs.decode('這狗\ u0001f602'.encode('utf-8'),'utf-8') 印刷(文字)#帶有...
    程式設計 發佈於2025-04-05
  • 如何將來自三個MySQL表的數據組合到新表中?
    如何將來自三個MySQL表的數據組合到新表中?
    mysql:從三個表和列的新表創建新表 答案:為了實現這一目標,您可以利用一個3-way Join。 選擇p。 *,d.content作為年齡 來自人為p的人 加入d.person_id = p.id上的d的詳細信息 加入T.Id = d.detail_id的分類法 其中t.taxonomy ...
    程式設計 發佈於2025-04-05
  • 我可以將加密從McRypt遷移到OpenSSL,並使用OpenSSL遷移MCRYPT加密數據?
    我可以將加密從McRypt遷移到OpenSSL,並使用OpenSSL遷移MCRYPT加密數據?
    將我的加密庫從mcrypt升級到openssl 問題:是否可以將我的加密庫從McRypt升級到OpenSSL?如果是這樣,如何? 答案:是的,可以將您的Encryption庫從McRypt升級到OpenSSL。 可以使用openssl。 附加說明: [openssl_decrypt()函數要求...
    程式設計 發佈於2025-04-05
  • Java是否允許多種返回類型:仔細研究通用方法?
    Java是否允許多種返回類型:仔細研究通用方法?
    在Java中的多個返回類型:一種誤解類型:在Java編程中揭示,在Java編程中,Peculiar方法簽名可能會出現,可能會出現,使開發人員陷入困境,使開發人員陷入困境。 getResult(string s); ,其中foo是自定義類。該方法聲明似乎擁有兩種返回類型:列表和E。但這確實是如此嗎...
    程式設計 發佈於2025-04-05
  • 如何在無序集合中為元組實現通用哈希功能?
    如何在無序集合中為元組實現通用哈希功能?
    在未訂購的集合中的元素要糾正此問題,一種方法是手動為特定元組類型定義哈希函數,例如: template template template 。 struct std :: hash { size_t operator()(std :: tuple const&tuple)const {...
    程式設計 發佈於2025-04-05
  • 為什麼PHP的DateTime :: Modify('+1個月')會產生意外的結果?
    為什麼PHP的DateTime :: Modify('+1個月')會產生意外的結果?
    使用php dateTime修改月份:發現預期的行為在使用PHP的DateTime類時,添加或減去幾個月可能並不總是會產生預期的結果。正如文檔所警告的那樣,“當心”這些操作的“不像看起來那樣直觀。 考慮文檔中給出的示例:這是內部發生的事情: 現在在3月3日添加另一個月,因為2月在2001年只有2...
    程式設計 發佈於2025-04-05
  • 如何使用不同數量列的聯合數據庫表?
    如何使用不同數量列的聯合數據庫表?
    合併列數不同的表 當嘗試合併列數不同的數據庫表時,可能會遇到挑戰。一種直接的方法是在列數較少的表中,為缺失的列追加空值。 例如,考慮兩個表,表 A 和表 B,其中表 A 的列數多於表 B。為了合併這些表,同時處理表 B 中缺失的列,請按照以下步驟操作: 確定表 B 中缺失的列,並將它們添加到表的...
    程式設計 發佈於2025-04-05
  • 為什麼使用Firefox後退按鈕時JavaScript執行停止?
    為什麼使用Firefox後退按鈕時JavaScript執行停止?
    導航歷史記錄問題:JavaScript使用Firefox Back Back 此行為是由瀏覽器緩存JavaScript資源引起的。要解決此問題並確保在後續頁面訪問中執行腳本,Firefox用戶應設置一個空功能。 警報'); }; alert('inline Alert')...
    程式設計 發佈於2025-04-05
  • 如何使用Regex在PHP中有效地提取括號內的文本
    如何使用Regex在PHP中有效地提取括號內的文本
    php:在括號內提取文本在處理括號內的文本時,找到最有效的解決方案是必不可少的。一種方法是利用PHP的字符串操作函數,如下所示: 作為替代 $ text ='忽略除此之外的一切(text)'; preg_match('#((。 &&& [Regex使用模式來搜索特...
    程式設計 發佈於2025-04-05
  • 如何處理PHP文件系統功能中的UTF-8文件名?
    如何處理PHP文件系統功能中的UTF-8文件名?
    在PHP的Filesystem functions中處理UTF-8 FileNames 在使用PHP的MKDIR函數中含有UTF-8字符的文件很多flusf-8字符時,您可能會在Windows Explorer中遇到comploreer grounder grounder grounder gro...
    程式設計 發佈於2025-04-05
  • 為什麼我的CSS背景圖像出現?
    為什麼我的CSS背景圖像出現?
    故障排除:CSS背景圖像未出現 ,您的背景圖像儘管遵循教程說明,但您的背景圖像仍未加載。圖像和样式表位於相同的目錄中,但背景仍然是空白的白色帆布。 而不是不棄用的,您已經使用了CSS樣式: bockent {背景:封閉圖像文件名:背景圖:url(nickcage.jpg); 如果您的html,cs...
    程式設計 發佈於2025-04-05
  • 為什麼PYTZ最初顯示出意外的時區偏移?
    為什麼PYTZ最初顯示出意外的時區偏移?
    與pytz 最初從pytz獲得特定的偏移。例如,亞洲/hong_kong最初顯示一個七個小時37分鐘的偏移: 差異源利用本地化將時區分配給日期,使用了適當的時區名稱和偏移量。但是,直接使用DateTime構造器分配時區不允許進行正確的調整。 example pytz.timezone(&#...
    程式設計 發佈於2025-04-05

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3