【问题标题】:flow function declaration syntax流函数声明语法
【发布时间】:2017-01-07 19:03:10
【问题描述】:

我正在尝试在我的声明文件中记录一个工厂函数。 我的目标是让 flow 了解我的简单工厂。

它在 koa v2 路由中使用,它是一种在我的服务中注入一些选项的方法。

这里是工厂:

ctx.compose = function Compose<T: *>(service: Class<T>, options: ?Object): T {
  return new service(_.extend({}, ctx._requestOptions, options));
};

因为我使用的是 koa v2,所以我在声明中创建了一个类型 KoaCtx,如下所示:

declare type KoaCtx = {
  params: { [key: string]: string },
  request: {
    query: { [key: string]: string },
    body: { [key: string]: string | boolean | Array<any> | Number | Date     | Object },
  },
  body: any,
  req: any,
  res: any,
  state: any,
  ...
  compose: compose: function <T: *>(service: Class<T>, options: ?Object): T
}

我尝试了不同的语法,但总是出错。

compose: function <T: *>(service: Class<T>, options: ?Object): T
                       ^ Unexpected token :

如果我将第一个 sn-p 代码放在我的 koa 路由中,它就可以正常工作! 我尝试在流程配置的 [include] 标记中添加带有 ctx.compose 定义的文件,但它不起作用。

更新

尝试使用此声明:

declare function Compose<T: *>(service: Class<T>, options: ?Object): T;

declare type KoaCtx = {
    ...
    compose: Compose<Class<*>>
};

但不幸的是,它仍然无法正常工作。

【问题讨论】:

    标签: flowtype


    【解决方案1】:

    函数类型看起来像

    (argName1: Type1, argName2: Type2, ...restName: Array<RestType>) => ReturnType
    

    具有泛型的函数类型看起来像

    <T>(argName1: Type1, argName2: Type2, ...restName: Array<RestType>) => ReturnType
    

    所以你可能应该写

    declare type KoaCtx = {
      ...
      compose: <T: *>(service: Class<T>, options: ?Object) => T
    }
    

    也就是说,您使用存在类型* 作为T 的上限。我不确定这在这里是否有意义。所以我只推荐写作

    declare type KoaCtx = {
      ...
      compose: <T>(service: Class<T>, options: ?Object) => T
    }
    

    至于您的更新,您只能显式实例化类型别名、接口和类的类型参数。所以你可以写

    declare type Compose = <T>(service: Class<T>, options: ?Object) => T;
    
    declare type KoaCtx = {
        ...
        compose: Compose<MyClass>
    };
    

    但如果 Compose 是通用函数,则不能这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 2021-12-04
      • 2021-06-13
      • 1970-01-01
      相关资源
      最近更新 更多