Skip to content

TypeScript Type Guards API

TypeScript 装饰器 —— 用于标注类及其成员的特殊声明(实验性)。

1 class · 4 methods

装饰器

4 methods

实验性装饰器(需要 experimentalDecorators)。Stage 3 ECMAScript 装饰器有所不同。

typeof x === 'string'

类装饰器。接收类构造函数;可返回替换类。

Parameters

NameTypeDescription
targetany被装饰的类构造函数。

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

NameTypeDescription
targetany原型(实例)或构造函数(静态)。
keyconstructor方法名。

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

NameTypeDescription
targetstring原型或构造函数。
keyobject属性名。

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

NameTypeDescription
targetany原型或构造函数。

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);
}