typescript 装饰器

Published: · LastMod: August 22, 2023 · 152 words

typescript 装饰器 🔗

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
declare type MethodDecorator = <T>(
  target: Object,
  propertyKey: string | symbol,
  descriptor: TypedPropertyDescriptor<T>
) => TypedPropertyDescriptor<T> | void

type VoidFn = ((...args: any[]) => void) | ((...args: any[]) => Promise<void>)
export const Performance = () => (target: any, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<VoidFn>) => {
  const originalMethod = descriptor.value
  if (originalMethod) {
    descriptor.value = function (this: any, ...args: any[]) {
      const handleError = (error: any) => {
        console.error(error)
        // etc.
      }
      const t1 = window.performance.now()
      try {
        const result: any = originalMethod.apply(this, args)
        const t2 = window.performance.now()
        console.log(`Performance time: ${t2 - t1}`)
        // @ts-ignore
        if (result && result instanceof Promise) {
          return result.catch(handleError)
        }
      } catch (error) {
        handleError(error)
      }
    }
    return descriptor
  }
}