繁体   English   中英

如何传递 function 中使用的泛型类型?

[英]How can I pass a generic type used in a function?

我在typescript中有一个 function 类型,如下所示:

export type NextFunType = <E, T>(event: E, context: Context) => Promise<T>;

然后我用NextFunType创建一个 function 如下:

const next: NextFunType = (event: string, context: Context) => {
  return Promise.resolve(true);
};

但我得到一个错误:

Type '(event: string, context: Context) => Promise<boolean>' is not assignable to type 'NextFunType'.
  Types of parameters 'event' and 'event' are incompatible.
    Type 'E' is not assignable to type 'string'

如何创建具有泛型类型的 function?

声明类型的正确方法是:

export type NextFunType<E, T> = (event: E, context: any) => Promise<T>;

当你初始化变量时,你需要传递ET的类型

 const next: NextFunType<string, boolean> = (event: string, context: any) => {
      return Promise.resolve(true);
    };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM