【问题标题】:Flow property is missing in mixed passed - despite the type annotation混合传递中缺少流属性 - 尽管有类型注释
【发布时间】:2020-07-27 05:43:25
【问题描述】:

我的声明文件中有以下内容(包含在我的 [libs] 中):

export type EtlFieldNoIdxT = {
  name: Name,
  purpose: Purpose,
}
export type EtlFieldT = {
  idx: number,
  ...EtlFieldNoIdxT
}

在我使用这些类型时有以下几点:


export const createEtlField = (
  etlFields: { [Name]: EtlFieldT },
  newField: EtlFieldNoIdxT,
) => {
  if (etlFields === {}) {
    throw new Error({
      message: 'Cannot create a new etlField with an empty etlFields',
    });
  }

  const field: EtlFieldT = {
    idx: maxId(etlFields, 'idx') + 1,
    ...newField,
  };

  const subject: Name = Object.values(etlFields).find(
    (f) => f.purpose === 'subject',     // <<< f.purpose "missing in mixed" error
  ).name;                               // <<<  .name "missing in mixed" error

  return newEtlField(field, subject);
};

尽管对输入进行了注释,但流能否推断出Object.values 将因此返回的类型?

提前感谢您指出我的误解。

-E

【问题讨论】:

    标签: flowtype


    【解决方案1】:

    如果您检查Object.values 的声明,您会发现它返回一个mixed 数组:

    static values(object: $NotNullOrVoid): Array&lt;mixed&gt;;


    一个快速的谷歌搜索回来了 https://davidwalsh.name/flow-object-values

    因此,为了解决您的问题,您将Object.values(...) 包装为any,然后在您的find arg 中您可以将其键入为EtlFieldT,最后在find 后将您的类型细化回EtlFieldT

    const subject: Name = ((Object.values(etlFields): any).find(
      (f: EtlFieldT) => f.purpose === 'subject',
    ): EtlFieldT).name;    
    

    尽管您应该知道find 有可能返回undefined。因此,为了正确起见,您应该运行find,如果值存在,则声明subject

    【讨论】:

      猜你喜欢
      • 2019-06-04
      • 1970-01-01
      • 2019-04-18
      • 2023-03-14
      • 1970-01-01
      • 2018-08-27
      • 2019-09-07
      • 2019-05-06
      • 1970-01-01
      相关资源
      最近更新 更多