AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

TypeScript 裝飾器實用指南!

來源: 責編: 時間:2023-08-09 23:03:20 254觀看
導讀一、裝飾器的概念 Summer IS HERE在 TypeScript 中,裝飾器就是可以添加到類及其成員的函數。TypeScript 裝飾器可以注釋和修改類聲明、方法、屬性和訪問器。Decorator類型定義如下:type Decorator = (target: Input, co

MtF28資訊網——每日最新資訊28at.com

一、裝飾器的概念 Summer IS HERE

在 TypeScript 中,裝飾器就是可以添加到類及其成員的函數。TypeScript 裝飾器可以注釋和修改類聲明、方法、屬性和訪問器。Decorator類型定義如下:MtF28資訊網——每日最新資訊28at.com

type Decorator = (target: Input, context: {  kind: string;  name: string | symbol;  access: {    get?(): unknown;    set?(value: unknown): void;  };  private?: boolean;  static?: boolean;  addInitializer?(initializer: () => void): void;}) => Output | void;

上面的類型定義解釋如下:MtF28資訊網——每日最新資訊28at.com

  • target:代表要裝飾的元素,其類型為 Input。
  • context 包含有關如何聲明修飾方法的元數據,即:
  • kind:裝飾值的類型。正如我們將看到的,這可以是類、方法、getter、setter、字段或訪問器。
  • name:被裝飾對象的名稱。
  • access:引用 getter 和 setter 方法來訪問裝飾對象的對象。
  • private:被裝飾的對象是否是私有類成員。
  • static:被修飾的對象是否是靜態類成員。
  • addInitializer:一種在構造函數開頭(或定義類時)添加自定義初始化邏輯的方法。
  • Output:表示 Decorator 函數返回值的類型。

二、裝飾器的類型 Summer IS HERE

接下來,我們就來了解一下裝飾器的各種類型。MtF28資訊網——每日最新資訊28at.com

Summer:類裝飾器

當將函數作為裝飾器附加到類時,將收到類構造函數作為第一個參數:MtF28資訊網——每日最新資訊28at.com

type ClassDecorator = (value: Function, context: {  kind: "class"  name: string | undefined  addInitializer(initializer: () => void): void}) => Function | void

例如,假設想要使用裝飾器向 Rocket 類添加兩個屬性:fuel 和 isEmpty()。在這種情況下,可以編寫以下函數:MtF28資訊網——每日最新資訊28at.com

function WithFuel(target: typeof Rocket, context): typeof Rocket {  if (context.kind === "class") {    return class extends target {      fuel: number = 50      isEmpty(): boolean {        return this.fuel == 0      }    }  }}

在確保裝飾元素的類型確實是類之后,返回一個具有兩個附加屬性的新類。或者,可以使用原型對象來動態添加新方法:MtF28資訊網——每日最新資訊28at.com

function WithFuel(target: typeof Rocket, context): typeof Rocket {  if (context.kind === "class") {    target.prototype.fuel = 50    target.prototype.isEmpty = (): boolean => {      return this.fuel == 0    }  }}

可以按以下方式使用 WithFuel:MtF28資訊網——每日最新資訊28at.com

@WithFuelclass Rocket {}const rocket = new Rocket()console.log((rocket as any).fuel)console.log(`empty? ${(rocket as any).isEmpty()}`)/* Prints:50empty? false*/

可以看到,這里將rocket轉換為any類型才能訪問新的屬性。這是因為裝飾器無法影響類型的結構。MtF28資訊網——每日最新資訊28at.com

如果原始類定義了一個稍后被裝飾的屬性,裝飾器會覆蓋原始值。例如,如果Rocket有一個具有不同值的fuel屬性,WithFuel裝飾器將會覆蓋該值:MtF28資訊網——每日最新資訊28at.com

function WithFuel(target: typeof Rocket, context): typeof Rocket {  if (context.kind === "class") {    return class extends target {      fuel: number = 50      isEmpty(): boolean {        return this.fuel == 0      }    }  }}@WithFuelclass Rocket {  fuel: number = 75}const rocket = new Rocket()console.log((rocket as any).fuel)// 50

Summer:方法裝飾器

方法裝飾器可以用于裝飾類方法。在這種情況下,裝飾器函數的類型如下:MtF28資訊網——每日最新資訊28at.com

type ClassMethodDecorator = (target: Function, context: {  kind: "method"  name: string | symbol  access: { get(): unknown }  static: boolean  private: boolean  addInitializer(initializer: () => void): void}) => Function | void

如果希望在調用被裝飾的方法之前或之后執行某些操作時,就可以使用方法裝飾器。MtF28資訊網——每日最新資訊28at.com

例如,在開發過程中,記錄對特定方法的調用或在調用之前/之后驗證前置/后置條件可能非常有用。此外,我們還可以影響方法的調用方式,例如通過延遲其執行或限制在一定時間內的調用次數。MtF28資訊網——每日最新資訊28at.com

最后,可以使用方法裝飾器將一個方法標記為已廢棄,并記錄一條消息來警告用戶,并告知他們應該使用哪個方法代替:MtF28資訊網——每日最新資訊28at.com

function deprecatedMethod(target: Function, context) {  if (context.kind === "method") {    return function (...args: any[]) {      console.log(`${context.name} is deprecated and will be removed in a future version.`)      return target.apply(this, args)    }  }}

在這種情況下,deprecatedMethod函數的第一個參數是要裝飾的方法。確認它確實是一個方法后(context.kind === "method"),返回一個新的函數,該函數在調用實際方法之前包裝被裝飾的方法并記錄一條警告消息。MtF28資訊網——每日最新資訊28at.com

接下來,可以按照以下方式使用裝飾器:MtF28資訊網——每日最新資訊28at.com

@WithFuelclass Rocket {  fuel: number = 75  @deprecatedMethod  isReadyForLaunch(): Boolean {    return !(this as any).isEmpty()  }}const rocket = new Rocket()console.log(`Is ready for launch? ${rocket.isReadyForLaunch()}`)

在isReadyForLaunch()方法中,引用了通過WithFuel裝飾器添加的isEmpty方法。注意,必須將其轉換為any類型的實例,與之前一樣。當調用isReadyForLaunch()方法時,會看到以下輸出,顯示警告消息被正確地打印出來:MtF28資訊網——每日最新資訊28at.com

isReadyForLaunch is deprecated and will be removed in a future version.Is the ready for launch? true

Summer:屬性裝飾器

屬性裝飾器與方法裝飾器的類型非常相似:MtF28資訊網——每日最新資訊28at.com

type ClassPropertyDecorator = (target: undefined, context: {  kind: "field"  name: string | symbol  access: { get(): unknown, set(value: unknown): void }  static: boolean  private: boolean}) => (initialValue: unknown) => unknown | void

屬性裝飾器的用例與方法裝飾器的用法也非常相似。例如,可以跟蹤對屬性的訪問或將其標記為已棄用:MtF28資訊網——每日最新資訊28at.com

function deprecatedProperty(_: any, context) {  if (context.kind === "field") {    return function (initialValue: any) {      console.log(`${context.name} is deprecated and will be removed in a future version.`)      return initialValue    }  }}

代碼與為方法定義的 deprecatedMethod 裝飾器非常相似,它的用法也是如此。MtF28資訊網——每日最新資訊28at.com

Summer:訪問器裝飾器

與方法裝飾器非常相似的是訪問器裝飾器,它是針對 getter 和 setter 的裝飾器:MtF28資訊網——每日最新資訊28at.com

type ClassSetterDecorator = (target: Function, context: {  kind: "setter"  name: string | symbol  access: { set(value: unknown): void }  static: boolean  private: boolean  addInitializer(initializer: () => void): void}) => Function | voidtype ClassGetterDecorator = (value: Function, context: {  kind: "getter"  name: string | symbol  access: { get(): unknown }  static: boolean  private: boolean  addInitializer(initializer: () => void): void}) => Function | void

訪問器裝飾器的定義與方法裝飾器的定義類似。例如,可以將 deprecatedMethod 和 deprecatedProperty 修飾合并到一個已棄用的函數中,該函數也支持 getter 和 setter:MtF28資訊網——每日最新資訊28at.com

function deprecated(target, context) {  const kind = context.kind  const msg = `${context.name} is deprecated and will be removed in a future version.`  if (kind === "method" || kind === "getter" || kind === "setter") {    return function (...args: any[]) {      console.log(msg)      return target.apply(this, args)    }  } else if (kind === "field") {    return function (initialValue: any) {      console.log(msg)      return initialValue    }  }}

三、裝飾器的用例 Summer IS HERE

上面介紹了裝飾器是什么以及如何正確使用它們,下面來看看裝飾器可以幫助我們解決的一些具體問題。MtF28資訊網——每日最新資訊28at.com

Summer:計算執行時間

假設想要估計運行一個函數需要多長時間,以此來衡量應用的性能。可以創建一個裝飾器來計算方法的執行時間并將其打印在控制臺上:MtF28資訊網——每日最新資訊28at.com

class Rocket {  @measure  launch() {    console.log("3... 2... 1...  
                

本文鏈接:http://www.tebozhan.com/showinfo-26-5177-0.htmlTypeScript 裝飾器實用指南!

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 六款開源、免費的簡歷制作神器,程序員必備!

下一篇: CSS 漸變中的顏色空間和色相插值

標簽:
  • 熱門焦點
  • 官方承諾:K60至尊版將會首批升級MIUI 15

    全新的MIUI 15今天也有了消息,在官宣了K60至尊版將會搭載天璣9200+處理器和獨顯芯片X7的同時,Redmi給出了官方承諾,K60至尊重大更新首批升級,會首批推送MIUI 15。也就是說雖然
  • Golang 中的 io 包詳解:組合接口

    io.ReadWriter// ReadWriter is the interface that groups the basic Read and Write methods.type ReadWriter interface { Reader Writer}是對Reader和Writer接口的組合,
  • 從零到英雄:高并發與性能優化的神奇之旅

    作者 | 波哥審校 | 重樓作為公司的架構師或者程序員,你是否曾經為公司的系統在面對高并發和性能瓶頸時感到手足無措或者焦頭爛額呢?筆者在出道那會為此是吃盡了苦頭的,不過也得
  • WebRTC.Net庫開發進階,教你實現屏幕共享和多路復用!

    WebRTC.Net庫:讓你的應用更親民友好,實現視頻通話無痛接入! 除了基本用法外,還有一些進階用法可以更好地利用該庫。自定義 STUN/TURN 服務器配置WebRTC.Net 默認使用 Google 的
  • 猿輔導與新東方的兩種“歸途”

    作者|卓心月 出品|零態LT(ID:LingTai_LT)如何成為一家偉大企業?答案一定是對“勢”的把握,這其中最關鍵的當屬對企業戰略的制定,且能夠站在未來看現在,即使這其中的
  • ESG的面子與里子

    來源 | 光子星球撰文 | 吳坤諺編輯 | 吳先之三伏大幕拉起,各地高溫預警不絕,但處于厄爾尼諾大“烤”之下的除了眾生,還有各大企業發布的ESG報告。ESG是“環境保
  • iQOO 11S新品發布會

    iQOO將在7月4日19:00舉行新品發布會,推出杭州亞運會電競賽事官方用機iQOO 11S。
  • 聯想小新Pad Pro 12.6將要推出,搭載高通驍龍 870 處理器

    聯想小新Pad Pro 12.6將于秋季新品會上推出,官方按照慣例直接在發布會前給出了機型的所有參數。聯想小新 Pad Pro 12.6 將搭載高通驍龍 870 處理器,重量為 5
  • SN570 NVMe SSD固態硬盤 價格與性能兼具

    SN570 NVMe SSD固態硬盤是西部數據發布的最新一代WD Blue系列的固態硬盤,不僅閃存技術更為精進,性能也得到了進一步的躍升。WD Blue SN570 NVMe SSD的包裝外
Top