如何通过打字稿类装饰右注入方法中额外的变量?

问题描述 投票:0回答:1

我正在学习打字稿及nest.js.

在这段代码中,我想注入额外变量的方法,当我需要它。

在此变卖我要过,我不使用后额外的变量。 (否则会出错“预计3个参数,但2”)

const iNeedInjectionObj = {}

const wowData = 'just wonderful'

function iNeedWow(target: any, name: string, index: number) {
  iNeedInjectionObj[name] = index
}

function classDecorator<T extends new (...args: any[]) => {}>(constructor: T) {
  const methods = constructor.prototype

  class Result extends constructor {
    constructor(...rest: any[]) {
      super(...rest)
      Object.keys(iNeedInjectionObj).forEach(
        methodName =>
          (this[methodName] = (...arr) => {
            const index = iNeedInjectionObj[methodName]
            arr.splice(index, 0, wowData)
            return methods[methodName](...arr)
          })
      )
    }
  }

  return Result
}

@classDecorator
class P {
  howIsMyCode(first, @iNeedWow here, second) {
    return first + here + second
  }
}
const p = new P()

console.log(
  p.howIsMyCode('You people ', ' and everybody know it', "I don't use this line")
)

也许我需要一个像一些通用的方法

(T&这里&U)=>空隙

但我不明白怎么写。

typescript
1个回答
0
投票

使用可选参数,并通过你在各种情况下需要的参数。只需添加一个问号“?”在参数名的末尾,以纪念这个参数可选。例如:

function getSchool(name: string, address?: string, pinCode?: string): string {
    //...
}

var school = getSchool("Elementary");
var school2 = getSchool("Little Kid", "UK");  
var school3 = getSchool("Rose Tree School", "US", "99501")
© www.soinside.com 2019 - 2024. All rights reserved.