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

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

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

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]刪除
最新教學 更多>
  • 如何將MySQL數據庫添加到Visual Studio 2012中的數據源對話框中?
    如何將MySQL數據庫添加到Visual Studio 2012中的數據源對話框中?
    在Visual Studio 2012 儘管已安裝了MySQL Connector v.6.5.4,但無法將MySQL數據庫添加到實體框架的“ DataSource對話框”中。為了解決這一問題,至關重要的是要了解MySQL連接器v.6.5.5及以後的6.6.x版本將提供MySQL的官方Visual...
    程式設計 發佈於2025-05-08
  • 如何處理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-05-08
  • Python元類工作原理及類創建與定制
    Python元類工作原理及類創建與定制
    python中的metaclasses是什麼? Metaclasses負責在Python中創建類對象。就像類創建實例一樣,元類也創建類。他們提供了對類創建過程的控制層,允許自定義類行為和屬性。 在Python中理解類作為對象的概念,類是描述用於創建新實例或對象的藍圖的對象。這意味著類本身是使用...
    程式設計 發佈於2025-05-08
  • 如何使用Java.net.urlConnection和Multipart/form-data編碼使用其他參數上傳文件?
    如何使用Java.net.urlConnection和Multipart/form-data編碼使用其他參數上傳文件?
    使用http request 上傳文件上傳到http server,同時也提交其他參數,java.net.net.urlconnection and Multipart/form-data Encoding是普遍的。 Here's a breakdown of the process:Mu...
    程式設計 發佈於2025-05-08
  • Java的Map.Entry和SimpleEntry如何簡化鍵值對管理?
    Java的Map.Entry和SimpleEntry如何簡化鍵值對管理?
    的綜合集合:在Java中介紹Java的Map.entry和SimpleEntry和SimpleEntry和SimpleEntry和SimpleEntry和SimpleEntry和SimpleEntry和SimpleEntry和SimpleEntry apry and Map。 地圖。它具有兩個通用...
    程式設計 發佈於2025-05-08
  • 您如何在Laravel Blade模板中定義變量?
    您如何在Laravel Blade模板中定義變量?
    在Laravel Blade模板中使用Elegance 在blade模板中如何分配變量對於存儲以後使用的數據至關重要。在使用“ {{}}”分配變量的同時,它可能並不總是最優雅的解決方案。 幸運的是,Blade通過@php Directive提供了更優雅的方法: $ old_section =...
    程式設計 發佈於2025-05-08
  • Android如何向PHP服務器發送POST數據?
    Android如何向PHP服務器發送POST數據?
    在android apache httpclient(已棄用) httpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost(“ http://www.yoursite.com/script.p...
    程式設計 發佈於2025-05-08
  • Java字符串非空且非null的有效檢查方法
    Java字符串非空且非null的有效檢查方法
    檢查字符串是否不是null而不是空的 if(str!= null && str.isementy())二手: if(str!= null && str.length()== 0) option 3:trim()。 isement(Isement() trim whitespace whites...
    程式設計 發佈於2025-05-08
  • 如何克服PHP的功能重新定義限制?
    如何克服PHP的功能重新定義限制?
    克服PHP的函數重新定義限制在PHP中,多次定義一個相同名稱的函數是一個no-no。嘗試這樣做,如提供的代碼段所示,將導致可怕的“不能重新列出”錯誤。 但是,PHP工具腰帶中有一個隱藏的寶石:runkit擴展。它使您能夠靈活地重新定義函數。 runkit_function_renction_...
    程式設計 發佈於2025-05-08
  • 為什麼使用固定定位時,為什麼具有100%網格板柱的網格超越身體?
    為什麼使用固定定位時,為什麼具有100%網格板柱的網格超越身體?
    網格超過身體,用100%grid-template-columns 為什麼在grid-template-colms中具有100%的顯示器,當位置設置為設置的位置時,grid-template-colly修復了? 問題: 考慮以下CSS和html: class =“ snippet-code”> ...
    程式設計 發佈於2025-05-08
  • 如何在Chrome中居中選擇框文本?
    如何在Chrome中居中選擇框文本?
    選擇框的文本對齊:局部chrome-inly-ly-ly-lyly solument 您可能希望將文本中心集中在選擇框中,以獲取優化的原因或提高可訪問性。但是,在CSS中的選擇元素中手動添加一個文本 - 對屬性可能無法正常工作。 初始嘗試 state)</option> < o...
    程式設計 發佈於2025-05-08
  • 解決Spring Security 4.1及以上版本CORS問題指南
    解決Spring Security 4.1及以上版本CORS問題指南
    彈簧安全性cors filter:故障排除常見問題 在將Spring Security集成到現有項目中時,您可能會遇到與CORS相關的錯誤,如果像“訪問Control-allo-allow-Origin”之類的標頭,則無法設置在響應中。為了解決此問題,您可以實現自定義過濾器,例如代碼段中的MyFi...
    程式設計 發佈於2025-05-08
  • 在PHP中如何高效檢測空數組?
    在PHP中如何高效檢測空數組?
    在PHP 中檢查一個空數組可以通過各種方法在PHP中確定一個空數組。如果需要驗證任何數組元素的存在,則PHP的鬆散鍵入允許對數組本身進行直接評估:一種更嚴格的方法涉及使用count()函數: if(count(count($ playerList)=== 0){ //列表為空。 } 對...
    程式設計 發佈於2025-05-08
  • Python中何時用"try"而非"if"檢測變量值?
    Python中何時用"try"而非"if"檢測變量值?
    使用“ try“ vs.” if”來測試python 在python中的變量值,在某些情況下,您可能需要在處理之前檢查變量是否具有值。在使用“如果”或“ try”構建體之間決定。 “ if” constructs result = function() 如果結果: 對於結果: ...
    程式設計 發佈於2025-05-08
  • HTML格式標籤
    HTML格式標籤
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    程式設計 發佈於2025-05-08

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

Copyright© 2022 湘ICP备2022001581号-3