装饰器
4 methods实验性装饰器(需要 experimentalDecorators)。Stage 3 ECMAScript 装饰器有所不同。
typeof x === 'string'类装饰器。接收类构造函数;可返回替换类。
Parameters
| Name | Type | Description |
|---|---|---|
| target | any | 被装饰的类构造函数。 |
Returns
boolean
Example
typescript
function len(x: string | number): number {
if (typeof x === 'string') {
return x.length; // x: string
}
return Math.abs(x); // x: number
}x instanceof Class方法装饰器。接收原型、方法名和属性描述符。
Parameters
| Name | Type | Description |
|---|---|---|
| target | any | 原型(实例)或构造函数(静态)。 |
| key | constructor | 方法名。 |
Returns
boolean
Example
typescript
function handle(e: Error | Date) {
if (e instanceof Error) {
console.log(e.message); // e: Error
} else {
console.log(e.getTime()); // e: Date
}
}'key' in obj属性装饰器。接收原型和属性名(无描述符)。
Parameters
| Name | Type | Description |
|---|---|---|
| target | string | 原型或构造函数。 |
| key | object | 属性名。 |
Returns
boolean
Example
typescript
type Cat = { meow: () => void };
type Dog = { bark: () => void };
function speak(animal: Cat | Dog) {
if ('meow' in animal) animal.meow(); // animal: Cat
else animal.bark(); // animal: Dog
}function isX(x: any): x is T参数装饰器。接收原型、方法名和参数索引。
Parameters
| Name | Type | Description |
|---|---|---|
| target | any | 原型或构造函数。 |
Returns
x is T
Example
typescript
function isString(x: any): x is string {
return typeof x === 'string';
}
function upper(x: unknown) {
if (isString(x)) {
return x.toUpperCase(); // x: string
}
return String(x);
}