以方法装饰器为例.
被装饰后的方法执行后会改变返回值.如何将这样的变更,使ts能够察觉到?
const ranger = (min: number, max: number) => Math.floor(Math.random()*(max-min+1)+min);
// 错误时,为方法返回值补充error字段
function Catch(target: any, key: string, descriptor: PropertyDescriptor) {
const fn = descriptor.value
descriptor.value = async function (...args: any[]) {
try {
return await fn.apply(this, args)
} catch (error) {
return {
code: 1,
error: [error.message || '异常']
}
}
}
return descriptor
}
// 被装饰的方法,可以安全得调用api.
class Test {
@Catch
async test() {
const value = ranger(0, 100)
if (value > 50) {
throw new Error('something went wrong')
}
return {code: 0, data: {value}}
}
}
const t = new Test()
t.test()
.then(res => {
// 然而这里无法知道res有error这个字段
})
ts虽然支持了装饰器,然而并没有正确地自动推断出被装饰后的方法返回值
https://github.com/Microsoft/...
搜了下,看起来目前是不行的。