TypeScript:从装饰器推断返回类型? [英] TypeScript: Inferring return type from a Decorator?
问题描述
当装饰器更改其返回类型时,如何让 TypeScript 推断装饰方法的类型?
How do I get TypeScript to infer the Type of a decorated method when the decorator changes it's return type?
在下面的基本示例中,我装饰了一个返回字符串化对象的方法:
In the basic example below, I decorate a method to return a stringified object:
function jsonStringify() {
return function (target, decoratedFnName: string, descriptor: PropertyDescriptor) {
let decoratedFn = descriptor.value;
let newFn = function () {
let object = decoratedFn.apply(target, arguments);
return JSON.stringify(object);
};
descriptor.value = newFn;
return descriptor;
}
}
class Decorated {
@jsonStringify()
method(name: string, description: string) {
return {
name: name,
description: description
}
}
};
let stringifiedObject = new Decorated().method('Test Name', 'Test Description');
console.log(stringifiedObject.includes('Test Name'));
如果我在 tsconfig.json 中使用 "noEmitOnError": false
转译 TypeScript,那么代码会完美运行并将 true 记录到控制台.但是,tsc 抱怨错误:
If I transpile the TypeScript with "noEmitOnError": false
in tsconfig.json, then the code runs perfectly and logs true to the console. However, tsc complains with the error:
error TS2339: Property 'includes' does not exist on type '{ name: string; description: string; }'.
我理解这是因为 Decorated.method()
返回一个对象而不是一个字符串,但是这个方法有一个返回一个字符串的装饰器.我需要做什么才能让 TypeScript 从装饰器推断类型?
Which I understand because Decorated.method()
returns an object and not a string, but this method has a decorator which returns a string. What do I need to do to get TypeScript to infer the type from the decorator?
推荐答案
目前不支持使用装饰器更改函数的返回类型.
It is not currently supported to change the return type of a function with a decorator.
在 github 上有一个 未解决的问题
There is an open issue on github tracking this
作为替代方案,您或许可以这样做:
As an alternative, you could perhaps do something like this:
class Decorated {
@jsonStringify()
method(name: string, description: string): string | object {
return {
name: name,
description: description
};
}
}
const stringifiedObject = new Decorated().method('Test Name', 'Test Description') as string;
console.log((stringifiedObject as string).includes('Test Name'));
但我知道这可能与您想要的有点不同
but I recognise this is probably a bit of a departure from what you were looking for
这篇关于TypeScript:从装饰器推断返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!