이 기사는 "TypeScript의 힘을 발표"하여 발췌 한 것으로, 이는 TypeScript 5.0에서 Decorator의 새로운 기능을 사용하는 방법을 보여줍니다.
더 이상 사용되지 않은 방법 중 하나를 기록하기위한 데코레이터를 만들어 봅시다.
이것은 언뜻보기에 약간 혼란 스러울 수 있지만 분해합시다.
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();
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; };
정적 : 클래스 요소가 정적인지 거짓인지를 나타내는 값.
위 내용은 빠른 팁 : TypeScript의 데코레이터의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!