前端面試十一之TS

TS 是 TypeScript 的縮寫,是一種由微軟開發的開源編程語言,它是 JavaScript 的一個超集,為 JavaScript 添加了類型系統和對 ES6+ 的支持。以下是關于 TypeScript 的詳細介紹:

一、特點

  • 類型系統:TypeScript 引入了類型注解,允許開發者為變量、函數參數、返回值等添加類型信息。這有助于在編譯階段發現潛在的類型錯誤,提高代碼的健壯性和可維護性。例如:

    let message: string = "Hello, TypeScript!";
    function add(a: number, b: number): number {return a + b;
    }

    在 TypeScript 中,typeinterface 都可以用來定義復雜數據類型,它們各有特點和適用場景,以下是詳細介紹:

二、使用?type?定義復雜數據類型

  • 基本語法
type TypeName = {property1: Type1;property2: Type2;// ...
};
  • 定義對象類型
type Person = {name: string;age: number;address: {street: string;city: string;};
};
  • 定義聯合類型
    type StringOrNumber = string | number;
  • 定義交叉類型:?
    type Employee = {employeeId: number;
    } & Person;
  • 定義泛型類型:?
    type Container<T> = {value: T;
    };

    三、使用?interface?定義復雜數據類型

  • 基本語法:?
    interface InterfaceName {property1: Type1;property2: Type2;// ...
    }
  • 定義對象類型:?
    interface Person {name: string;age: number;address: {street: string;city: string;};
    }
  • 定義類類型:?
    interface Person {name: string;age: number;greet(): void;
    }
    class Student implements Person {name: string;age: number;constructor(name: string, age: number) {this.name = name;this.age = age;}greet() {console.log(`Hello, my name is ${this.name}`);}
    }

    type?與?interface?的區別與選擇

  • 區別

    • type 是類型別名,可以為任何類型定義一個新的名字,包括基本類型、聯合類型、交叉類型等;而 interface 主要用于定義對象類型或類類型。

    • interface 可以被類實現(implements),而 type 不行。

    • interface 可以繼承其他接口,而 type 不行。

    • type 定義的類型可以使用交叉類型(&)來組合多個類型,而 interface 只能繼承一個接口。

  • 選擇

    • 如果需要定義一個對象類型或類類型,并且希望使用繼承或類實現,建議使用 interface

    • 如果需要定義聯合類型、交叉類型或泛型類型,或者需要為復雜類型定義別名,建議使用 type

    • 在實際開發中,可以根據具體需求和團隊編碼規范來選擇使用 typeinterface

四、 函數類型

在 TypeScript 中,函數類型用于描述函數的參數類型和返回值類型。你可以通過類型別名(type)或接口(interface)來定義函數類型。?

interface Api {foo(): void;bar(str: string): string;
}function test(api: Api) {api.foo();const result = api.bar("hello");console.log(result);
}// 調用 test 函數
test({foo() {console.log('ok');},bar(str: string) {return str.toUpperCase();}
});

五、字面量與nullish類型

// 字面量類型:功能:輸出一段文字(參數1),參數2決定文字的對齊方式
function printText(text: string, alignment: "left" | "right" | "center") {console.log(text, alignment);
}printText("Hello", "left");
printText("Hello", "center");// nullish 類型 null undefined
function test(x?: string | null) {// if (x !== null && x !== undefined)// console.log(x.toUpperCase());  // 錯誤:x 可能為 null 或 undefinedconsole.log(x?.toUpperCase());   // 正確:使用可選鏈
}test("hello");
test(null);
test();

六、泛型

interface Ref<T> {value: T;
}const r1: Ref<string> = { value: 'hello' };
const r2: Ref<number> = { value: 123 };
const r3: Ref<boolean> = { value: true };function test1(n: string) {return { value: n };
}function test2(n: number) {return { value: n };
}function ref<T>(n: T): Ref<T> {return { value: n };
}const v1 = ref("hello");      // Ref<string>
const v2 = ref(123.3333);     // Ref<number>
console.log(v2.value.toFixed(2));  // 輸出: 123.33

?七、class語法

一個基本的類定義包括類名、屬性(成員變量)和方法(成員函數):

class Person {// 類屬性(成員變量)firstName: string;lastName: string;// 構造函數constructor(firstName: string, lastName: string) {this.firstName = firstName;this.lastName = lastName;}// 類方法(成員函數)fullName(): string {return `${this.firstName} ${this.lastName}`;}
}

繼承

TypeScript 支持類的繼承,可以使用 extends 關鍵字來實現:

class Employee extends Person {employeeId: number;constructor(firstName: string, lastName: string, employeeId: number) {super(firstName, lastName);  // 調用父類的構造函數this.employeeId = employeeId;}work(): string {return `${this.fullName()} is working`;}
}

訪問修飾符

TypeScript 提供了三種訪問修飾符:

  • public:公共的,可以在任何地方訪問。

  • private:私有的,只能在類內部訪問。

  • protected:受保護的,可以在類內部和子類中訪問。

    class Person {private name: string;constructor(name: string) {this.name = name;}public getName(): string {return this.name;}
    }

    抽象類

    抽象類是不能被實例化的類,通常用作基類:

    abstract class Animal {abstract makeSound(): void;move(): void {console.log("Moving");}
    }class Dog extends Animal {makeSound(): void {console.log("Bark");}
    }

    靜態成員

    類可以包含靜態屬性和方法,這些成員屬于類本身,而不是類的實例:

    class Utils {static pi: number = 3.14;static calculateCircleArea(radius: number): number {return Utils.pi * radius * radius;}
    }

    類表達式

    類也可以作為表達式定義,這在定義匿名類時非常有用:

    const Animal = class {makeSound() {console.log("Some generic sound");}
    };const dog = new Animal();
    dog.makeSound();  // 輸出: Some generic sound

    類類型

    類本身可以作為類型使用:

    let person: Person;
    person = new Person("Alice", "Smith");

    類與接口

    類可以實現接口,接口定義了類必須遵循的結構:

    interface Greeting {greet(): string;
    }class Hello implements Greeting {greet(): string {return "Hello";}
    }

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/88958.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/88958.shtml
英文地址,請注明出處:http://en.pswp.cn/web/88958.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Excel快捷鍵

Excel快捷鍵可以快速提高使用Excel的效率&#xff0c;下面將Excel快捷鍵進行整理匯總以備不時之需 標注顏色的為需要經常使用并可以顯著提高效率的快捷鍵 Ctrl相關快捷鍵【Ctrl】【1】 顯示【單元格格式】設置窗口,可以設置選中的格式【Ctrl】【2】 應用或取消加粗…

Windows 10/11安裝WSL、Ubuntu、Docker Desktop

WSL&#xff0c;Windows Subsystem for Linux&#xff0c;是微軟開發的輕量級虛擬機環境&#xff0c;允許用戶在 Windows上運行完整的Linux內核和用戶空間&#xff0c;適用于Windows的Linux子系統。能實現&#xff1a; 運行原生的Linux命令和程序&#xff08;如apt&#xff0c…

React之旅-06 Ref

當你想讓一個組件“記住”一些信息&#xff0c;但又不想這些信息觸發新的渲染時&#xff0c;你可以使用 ref。使用 Ref 前&#xff0c;需要導入useRef&#xff0c;代碼如下&#xff1a;import { useRef } from react;在您的組件內部&#xff0c;調用 useRef 并將您想要引用的初…

stm32-Modbus主機移植程序理解以及實戰

目錄一、背景二、代碼理解&#xff08;一&#xff09;main()函數例程代碼功能遇到的問題解決方式分析&#xff08;二&#xff09;eMBMasterPoll( void )函數例程代碼1. 變量聲明2. 協議棧狀態檢查3. 獲取事件4. 事件處理&#xff08;switch-case&#xff09;4.1 EV_MASTER_READ…

c++判斷文件或目錄是否存在

#include<sys/stat.h>#include<fstream>#include<string>#include<stdio.h>#include<stdlib.h>#include<vector>#include<io.h>#include<iostream>bool IsFileGood(string strFileName, book bFile){if(bFile) \\文件{ifstrea…

Java設計模式之行為型模式(命令模式)

一、核心定義與設計思想 命令模式通過對象化請求&#xff0c;將操作的具體實現細節封裝在命令對象中&#xff0c;使得調用者&#xff08;Invoker&#xff09;無需直接依賴接收者&#xff08;Receiver&#xff09;&#xff0c;僅需通過命令對象間接調用。這種設計支持以下能力&a…

大數據領域開山鼻祖組件Hadoop核心架構設計

一、Hadoop的整體架構 Hadoop是一個專為大數據設計的架構解決方案&#xff0c;歷經多年開發演進&#xff0c;已逐漸發展成為一個龐大且復雜的系統。其內部工作機制融合了分布式理論與具體工程開發的精髓&#xff0c;構成了一個整體架構。 Hadoop最樸素的原理在于&#xff0c;它…

OneCode3.0 VFS分布式文件管理API速查手冊

&#x1f4da; 前言&#xff1a;OneCode 3.0微內核引擎架構解析 在云原生與分布式系統日益普及的今天&#xff0c;文件管理系統面臨著前所未有的挑戰——海量數據存儲、跨節點協同、多租戶隔離以及彈性擴展等需求推動著傳統文件系統向分布式架構演進。OneCode 3.0作為新一代企業…

UI前端與數字孿生結合實踐探索:智慧物流的倉儲自動化管理系統

hello寶子們...我們是艾斯視覺擅長ui設計、前端開發、數字孿生、大數據、三維建模、三維動畫10年經驗!希望我的分享能幫助到您!如需幫助可以評論關注私信我們一起探討!致敬感謝感恩!一、引言&#xff1a;傳統倉儲的 “效率黑洞” 與數字孿生的破局當倉庫管理員在數萬平的庫房中…

使用layui的前端框架過程中,無法加載css和js怎么辦?

這使用layui的前端框架過程中&#xff0c;無法加載css和js怎么辦&#xff1f;里寫自定義目錄標題已經按要求下載并解壓到指定位置了&#xff0c;但是感覺就是無法加載文件后臺提示如下&#xff1a;那就我清理緩存當再次觀察html頁面時&#xff0c;發現頁面最開始有兩個< htm…

gitlab+TortoiseGit克隆生成ppk方式

1、第一步 2、第二步3、第三步4、第四步&#xff0c;如何使用這個ppk就可以了

VSCode中使用容器及容器編排docker-compose

前面筆者寫了一篇博文&#xff1a;使用容器編排對go項目進行部署、調試&#xff0c;介紹了在Goland中如何使用容器&#xff0c;由于Goland的容器配置是可視化的&#xff0c;使用起來非常方便&#xff0c;VSCode中也有一個容器插件&#xff0c;但是筆者一直未使用過&#xff0c;…

深度學習入門:讓神經網絡變得“深不可測“?(二)

深度學習入門&#xff1a;讓神經網絡變得"深不可測" &#x1f9e0;? 系列課程第二彈&#xff1a;深度學習的奇妙世界 前言&#xff1a;從淺到深的華麗轉身 哈嘍&#xff0c;各位AI探險家&#xff01;&#x1f44b; 歡迎回到我們的"讓機器變聰明"系列課…

硅基計劃2.0 學習總結 捌 異常與常用工具類

文章目錄一、異常1. 防御性編程2. throw關鍵字3. throws關鍵字4. 捕獲5. finally關鍵字二、自定義異常類三、常用工具類1. Date以及相關的類1. 創建時間&#xff08;基本棄用&#xff09;2. 捕獲系統時間3. 獲取當前年月日時分秒4. 日期加減5. 根據字符串創建日期6. 根據當前時…

2025-7-14-C++ 學習 排序(2)

文章目錄2025-7-14-C 學習 排序&#xff08;2&#xff09;P1059 [NOIP 2006 普及組] 明明的隨機數題目描述輸入格式輸出格式輸入輸出樣例 #1輸入 #1輸出 #1說明/提示提交代碼P1093 [NOIP 2007 普及組] 獎學金題目背景題目描述輸入格式輸出格式輸入輸出樣例 #1輸入 #1輸出 #1輸入…

微信131~140

1.在組件中使用store對象的數據 // 要想使用store中的數據以及方法 // 需要從 mobx-miniprogram-bindings 方法將 ComponentWithStore 方法 import { ComponentWithStore } from mobx-miniprogram-bindings // 導入store對象 import { numStore } from ../../../stores/numstor…

微美全息借區塊鏈與DRL算法打造資源管理協同架構,達成邊緣計算與區塊鏈動態適配

在當今數字化浪潮洶涌的時代&#xff0c;邊緣計算與區塊鏈技術正逐步成為驅動技術革新與業務轉型升級的核心動力。當這兩項前沿技術相互融合&#xff0c;一個兼具高效性與安全性的任務處理系統便得以構建。為了充分挖掘邊緣計算系統的性能潛力&#xff0c;避免任務卸載過程中的…

屬性綁定

簡寫模式二.為什么要這樣做布爾型attribute動態綁定多個值

鏈表算法之【獲取鏈表開始入環的節點】

目錄 LeetCode-142題 LeetCode-142題 給定一個鏈表的頭節點head&#xff0c;返回鏈表開始入環的第一個節點&#xff0c;如果鏈表無環&#xff0c;則返回null class Solution {public ListNode detectCycle(ListNode head) {// checkif (head null || head.next null)retur…

【網絡編程】KCP——可靠的 UDP 傳輸協議——的知識匯總

文章目錄前言UDP 協議UDP 的關鍵指標/特性UDP 的典型應用場景KCP 協議的基礎KCP 的構造KCP 協議特性KCP 的可靠傳輸機制——ARQ三種 ARQ 機制對比KCP 的選擇性重傳一、基礎機制&#xff1a;選擇性重傳&#xff08;SR&#xff09;二、KCP 對 SR 的增強策略KCP 的激進重傳策略——…