是否可以在装饰器函数中使用函数的返回值?

Mar*_*ras 1 typescript typescript-decorator

我想使用函数的输出值作为该函数正在使用的装饰器的输入。例如,类似的事情:

function dec(otherFuncOutput: string) {
  console.log(otherFuncOutput)
}

@dec
function otherFunc(): string {
  const otherFuncOutput: string = "output";
  return otherFuncOutput;
}
Run Code Online (Sandbox Code Playgroud)

这样做的正确方法是什么?

Ale*_*yne 6

Typescript 装饰器可以应用于类声明、方法、访问器、属性或参数,但不能应用于普通函数,因此我假设您想使用类方法来执行此操作。

因此,要做到这一点,您需要检查属性描述符,获取它描述的函数值,并将其替换为调用原始函数并对其输出执行某些操作的新函数。

function dec(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  // Check of the decorated property is a function
  if (typeof descriptor.value === 'function') {
    // The function that we are going to wrap
    const declaredFn = descriptor.value

    // Provide a new function for this property that wraps the original function
    descriptor.value = () => {
      // Call the method with `this` set the object with the method,
      // in case that matters.
      const result = declaredFn.apply(target)

      // Do the thing you want with the result
      console.log(result)

      // Return the result from the origin function
      return result
    }
  }
}

class A {
  @dec
  otherFunc(): string {
    const otherFuncOutput = 'output'
    return otherFuncOutput
  }
}

new A().otherFunc() // logs "output"
Run Code Online (Sandbox Code Playgroud)

操场