TypeScript装饰器的使用与实践
1. 装饰器基础与类型匹配问题
装饰器是TypeScript中强大的特性,可用于修改类、方法、字段等。 time 装饰器被应用到方法上时,会为每个被装饰的方法调用一次 time 函数,返回的替换方法将替代原类中定义的方法。
例如,在 Product 类中添加方法:
import { time } from "./methodDecorator.js";
export class Product {
constructor(public name: string, public price: number) {}
@time
getDetails(): string {
return `Name: ${this.name}, Price: $${this.price}`;
}
@time
getPrice(): number {
return this.price;
}
}
这里会出现编译错误,因为 time 装饰器返回的替换方法返回类型为 string ,而 getPrice 方法返回类型为 number ,类型不匹配。错误信息如下:
src/product.ts(12,6): error TS1270:
超级会员免费看
订阅专栏 解锁全文
1317

被折叠的 条评论
为什么被折叠?



