TypeScript 5.0 中的装饰器:优雅地修改类和方法
本文节选自《释放TypeScript的威力》,将向您展示如何在TypeScript 5.0中使用装饰器这一新特性。
装饰器几乎一直是ECMAScript的一部分。这些简洁的工具允许我们以可重用的方式修改类和成员。它们在TypeScript中已经存在一段时间了——尽管是在实验性标志下。虽然装饰器的Stage 2迭代一直是实验性的,但它们已被广泛应用于MobX、Angular、Nest和TypeORM等库中。TypeScript 5.0的装饰器与ECMAScript提案完全同步,已经非常成熟,处于Stage 3阶段。
装饰器允许我们创建一个函数,该函数可以调整类及其方法的行为。假设我们需要在方法中添加一些调试语句。在TypeScript 5.0之前,我们只能手动在每个方法中复制粘贴调试语句。使用装饰器,我们只需操作一次,更改就会应用于装饰器附加的每个方法。
让我们创建一个用于记录给定方法已弃用的装饰器:
<code class="language-typescript">class Card { constructor(public suit: Suit, public rank: Rank) { this.suit = suit; this.rank = rank; } get name(): CardName { return `${this.rank} of ${this.suit}`; } @deprecated // ? 这是一个装饰器! getValue(): number { if (this.rank === 'Ace') return 14; if (this.rank === 'King') return 13; if (this.rank === 'Queen') return 12; if (this.rank === 'Jack') return 11; return this.rank; } // 新的实现方式! get value(): number { if (this.rank === 'Ace') return 14; if (this.rank === 'King') return 13; if (this.rank === 'Queen') return 12; if (this.rank === 'Jack') return 11; return this.rank; } } const card = new Card('Spades', 'Queen'); card.getValue();</code>
我们希望每当调用card.getValue()时,都会向控制台记录一条警告消息。我们可以如下实现上述装饰器:
<code class="language-typescript">const deprecated = <this arguments extends any returnvalue>( target: (this: This, ...args: Arguments) => ReturnValue, context: ClassMethodDecoratorContext<returnvalue> ) => { const methodName = String(context.name); function replacementMethod(this: This, ...args: Arguments): ReturnValue { console.warn(`Warning: '${methodName}' is deprecated.`); return target.call(this, ...args); } return replacementMethod; };</returnvalue></this></code>
乍一看这可能有点令人困惑,但让我们分解一下:
ClassMethodDecorator类型具有以下属性:
您可以在此playground中测试上面的代码示例。
装饰器为添加日志消息(如我们在上面的示例中所做的那样)以及许多其他常见用例提供了方便的语法糖。例如,我们可以创建一个装饰器,该装饰器会自动将方法绑定到当前实例,或者修改方法或类的属性描述符。
本文节选自《释放TypeScript的威力》,可在SitePoint Premium和电子书零售商处购买。
以上是快速提示:打字稿中的装饰器的详细内容。更多信息请关注PHP中文网其他相关文章!