代码之家  ›  专栏  ›  技术社区  ›  Tom Hudson

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

  •  3
  • Tom Hudson  · 技术社区  · 7 年前

    如何让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'));
    

    如果我用 "noEmitOnError": false 在tsconfig中。json,则代码可以完美运行,并在控制台中记录true。然而,tsc投诉错误:

    error TS2339: Property 'includes' does not exist on type '{ name: string; description: string; }'.
    

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

    1 回复  |  直到 7 年前
        1
  •  5
  •   Stewart_R    7 年前

    当前不支持使用修饰符更改函数的返回类型。

    有一个 open issue on github tracking 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'));
    

    但我认识到这可能有点偏离了你想要的