【问题标题】:Flow property missing in object type对象类型中缺少流属性
【发布时间】:2023-03-14 09:34:01
【问题描述】:

我有以下 Flow Props 类型的组件:

type Props = {
  // <...>
  update: ({ dates?: DateRange }) => void
};

我还有以下导出类型:

export type SearchContextType = {
  // <...>
  update: ({ dates?: DateRange, location?: Location }) => void
};

当我尝试使用第二种类型将道具传递给第一个组件时,我收到以下错误:

错误:(99, 23) 无法创建 MyComponent 元素,因为属性 location 在对象类型 1 中缺失,但在属性 update 的第一个参数中的对象类型 [2] 中存在。

我理解这个错误,但我的问题是:我怎样才能正确地绕过它?

Example

【问题讨论】:

  • 也许你应该分享你使用类型的实际代码?
  • 我已经设置了 Flow try repo,但我无法重现您的问题,请随时编辑,不要忘记选择您的 Flow 版本:flow.org/try/…

标签: reactjs flowtype


【解决方案1】:

首先 - 我们将简化示例:

type SubType = { dates?: string, location?: string };
type Foo = (arg: SubType) => void;

type SuperType = { dates?: string };
type Bar = (arg: SuperType) => void;

function convert (arg: Foo): Bar {
  return arg;
  //     ^ Cannot return `arg` because property `location` is missing in `SuperType` [1] but exists in `SubType` [2] in the first argument.
}

换句话说,我们只是使用类型转换将Foo 转换为Bar:

const anyObj = ({}: any);

((anyObj: Foo): Bar);
//        ^ Cannot cast object literal to `Bar` because property `location` is missing in `SuperType` [1] but exists in `SubType` [2] in the first argument.

或者我们可以说我们将SuperType转换成SubType

((anyObj: SuperType): SubType);
//        ^ Cannot cast `anyObj` to `SubType` because property `location` is missing in `SuperType` [1] but exists in `SubType` [2].

要将SuperType 转换为SubType,我们可以使用$Shape:

复制所提供类型的形状,但将每个字段标记为可选。

// Correct
((anyObj: SuperType): $Shape<SubType>);

TLDR:

export type SearchContextType = {
  dates: DateRange,
  location: GoogleMapPosition,
  update: ($Shape<{ dates?: DateRange, location?: GoogleMapPosition }>) => void
  //       ^ add `$Shape`
};

Corrected Example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 2017-02-15
    • 2015-12-02
    • 2019-02-07
    相关资源
    最近更新 更多