【问题标题】:Generic function type is not applied to the returned object members泛型函数类型不适用于返回的对象成员
【发布时间】:2019-09-17 19:39:35
【问题描述】:

我正在定义一个函数,它返回一个对象,该对象的成员是具有相同有效负载的函数。 Payload 类型是通过generic 定义的,它扩展了对象。但是,流程抱怨泛型类型不同然后通过:

export const getObj = <T: {}>(url: string) => ({
  create: (entity: T) => console.log(url, entity),
  ...
});

const url = '/some-path';

type TEntity = {
  some: string,
};

const entity: TEntity = {
  some: 'value',
};

const instance = getObj<TEntity>(url);

instance.create(entity);

流量抱怨:

^ 无法在 entity 绑定到 entity 时调用 instance.create,因为 TEntity 2T 2 不兼容。

Try.

我做错了什么?

【问题讨论】:

  • 那你为什么不把create设置成Tentity呢? create: (entity: TEntity)
  • 起初,b/c 我也需要 getObj&lt;TOtherEntity&gt;getObj&lt;TVeryOtherEntity&gt; 的方式(以及许多其他方式)。第二个是 b/c 除了create,还有其他方法需要相同的类型才能正确定义。他们按照您的建议,这将是大量的复制粘贴。 @基思
  • 我还没有一个完整的答案,但是我通过用T 声明getObj 的返回类型而不是用T 内联注释来让Flow 运行。现在是Try Flow,但我希望尽快找到真正的答案。
  • @user11307804,是的,我觉得定义返回类型可能是一个可以接受的解决方法。奇怪的是流量自己算不出来……

标签: javascript types flowtype


【解决方案1】:

如有疑问,be more explicit.

// @flow

type EntityFactory<T> = $ReadOnly<{|
  create: (T) => void,
|}>;

export const getObj = <T>(url: string): EntityFactory<T> => ({
  create: (entity: T) => console.log(url, entity),
});

const url = '/some-path';

type TEntity = {
  some: string,
};

const entity: TEntity = {
  some: 'value',
};

const instance = getObj<TEntity>(url);

instance.create(entity);

【讨论】:

  • 请不要试图通过链接变得可爱。如果将来由于某种原因该链接不再起作用,this answer would not be helpful to anyone。直接在您的答案中提供相关代码作为代码块。
  • 这让我对 StackOverflow 格式感到沮丧。我是一个有问题答案的人,但也太忙了,无法很好地回答问题。如果我对问题留下格式不正确的答案,那么可能发生的最坏情况是什么?我会被禁止还是什么?对于想要提供帮助但又不想投入足够工作以使答案变得真正好的用户,SO 会怎么做?
猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多