我正在学习打字稿和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&Here&U)=>无效
但是我不知道怎么写。
答案 0 :(得分: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")