TypeScript:从装饰器推断返回类型?

Tom*_*son 5 typescript typescript-typings

当装饰器更改其返回类型时,如何让 TypeScript 推断装饰方法的类型?

在下面的基本示例中,我装饰一个方法以返回字符串化对象:

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'));
Run Code Online (Sandbox Code Playgroud)

如果我在 tsconfig.json 中转译 TypeScript "noEmitOnError": false,那么代码将完美运行并在控制台中记录 true。然而,tsc 抱怨错误:

error TS2339: Property 'includes' does not exist on type '{ name: string; description: string; }'.
Run Code Online (Sandbox Code Playgroud)

我理解这是因为Decorated.method()返回一个对象而不是字符串,但是这个方法有一个返回字符串的装饰器。我需要做什么才能让 TypeScript 从装饰器推断类型?

Ste*_*t_R 6

目前不支持使用装饰器更改函数的返回类型。

github 上有一个未解决的问题跟踪此问题

作为替代方案,您也许可以这样做:

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'));
Run Code Online (Sandbox Code Playgroud)

但我认识到这可能与您正在寻找的内容有点背离