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

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

TypeScript 裝飾器實用指南!

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

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

一、裝飾器的概念 Summer IS HERE

在 TypeScript 中,裝飾器就是可以添加到類及其成員的函數。TypeScript 裝飾器可以注釋和修改類聲明、方法、屬性和訪問器。Decorator類型定義如下:p7W28資訊網——每日最新資訊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;

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

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

二、裝飾器的類型 Summer IS HERE

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

Summer:類裝飾器

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

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

例如,假設想要使用裝飾器向 Rocket 類添加兩個屬性:fuel 和 isEmpty()。在這種情況下,可以編寫以下函數:p7W28資訊網——每日最新資訊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      }    }  }}

在確保裝飾元素的類型確實是類之后,返回一個具有兩個附加屬性的新類。或者,可以使用原型對象來動態添加新方法:p7W28資訊網——每日最新資訊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:p7W28資訊網——每日最新資訊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類型才能訪問新的屬性。這是因為裝飾器無法影響類型的結構。p7W28資訊網——每日最新資訊28at.com

如果原始類定義了一個稍后被裝飾的屬性,裝飾器會覆蓋原始值。例如,如果Rocket有一個具有不同值的fuel屬性,WithFuel裝飾器將會覆蓋該值:p7W28資訊網——每日最新資訊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:方法裝飾器

方法裝飾器可以用于裝飾類方法。在這種情況下,裝飾器函數的類型如下:p7W28資訊網——每日最新資訊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

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

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

最后,可以使用方法裝飾器將一個方法標記為已廢棄,并記錄一條消息來警告用戶,并告知他們應該使用哪個方法代替:p7W28資訊網——每日最新資訊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"),返回一個新的函數,該函數在調用實際方法之前包裝被裝飾的方法并記錄一條警告消息。p7W28資訊網——每日最新資訊28at.com

接下來,可以按照以下方式使用裝飾器:p7W28資訊網——每日最新資訊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()方法時,會看到以下輸出,顯示警告消息被正確地打印出來:p7W28資訊網——每日最新資訊28at.com

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

Summer:屬性裝飾器

屬性裝飾器與方法裝飾器的類型非常相似:p7W28資訊網——每日最新資訊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

屬性裝飾器的用例與方法裝飾器的用法也非常相似。例如,可以跟蹤對屬性的訪問或將其標記為已棄用:p7W28資訊網——每日最新資訊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 裝飾器非常相似,它的用法也是如此。p7W28資訊網——每日最新資訊28at.com

Summer:訪問器裝飾器

與方法裝飾器非常相似的是訪問器裝飾器,它是針對 getter 和 setter 的裝飾器:p7W28資訊網——每日最新資訊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:p7W28資訊網——每日最新資訊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

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

Summer:計算執行時間

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

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

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

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

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

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

標簽:
  • 熱門焦點
  • 一文看懂為蘋果Vision Pro開發應用程序

    譯者 | 布加迪審校 | 重樓蘋果的Vision Pro是一款混合現實(MR)頭戴設備。Vision Pro結合了虛擬現實(VR)和增強現實(AR)的沉浸感。其高分辨率顯示屏、先進的傳感器和強大的處理能力
  • Golang 中的 io 包詳解:組合接口

    io.ReadWriter// ReadWriter is the interface that groups the basic Read and Write methods.type ReadWriter interface { Reader Writer}是對Reader和Writer接口的組合,
  • 學習JavaScript的10個理由...

    作者 | Simplilearn編譯 | 王瑞平當你決心學習一門語言的時候,很難選擇到底應該學習哪一門,常用的語言有Python、Java、JavaScript、C/CPP、PHP、Swift、C#、Ruby、Objective-
  • 使用LLM插件從命令行訪問Llama 2

    最近的一個大新聞是Meta AI推出了新的開源授權的大型語言模型Llama 2。這是一項非常重要的進展:Llama 2可免費用于研究和商業用途。(幾小時前,swyy發現它已從LLaMA 2更名為Lla
  • 這款新興工具平臺,讓你的電腦效率翻倍

    隨著信息技術的發展,我們獲取信息的渠道越來越多,但是處理信息的效率卻成為一個瓶頸。于是各種工具應運而生,都在爭相解決我們的工作效率問題。今天我要給大家介紹一款效率
  • 從零到英雄:高并發與性能優化的神奇之旅

    作者 | 波哥審校 | 重樓作為公司的架構師或者程序員,你是否曾經為公司的系統在面對高并發和性能瓶頸時感到手足無措或者焦頭爛額呢?筆者在出道那會為此是吃盡了苦頭的,不過也得
  • 三星獲批量產iPhone 15全系屏幕:蘋果史上最驚艷直屏

    按照慣例,蘋果將繼續在今年9月舉辦一年一度的秋季新品發布會,有傳言稱發布會將于9月12日舉行,屆時全新的iPhone 15系列將正式與大家見面,不出意外的話
  • 上海舉辦人工智能大會活動,建設人工智能新高地

    人工智能大會在上海浦江兩岸隆重拉開帷幕,人工智能新技術、新產品、新應用、新理念集中亮相。8月30日晚,作為大會的特色活動之一的上海人工智能發展盛典人工
  • Meta盲目擴張致超萬人被裁,重金押注元宇宙而前景未明

    圖片來源:圖蟲創意日前,Meta創始人兼CEO 馬克·扎克伯發布公開信,宣布Meta計劃裁員超11000人,占其員工總數13%。他公開承認了自己的預判失誤:“不僅
Top