对象类型中缺少流属性

时间:2018-07-08 11:02:35

标签: reactjs flowtype

对于组件,我具有以下流程Props类型:

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

我还具有以下导出类型:

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

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

  

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

我理解该错误,但我的问题是:如何正确解决该问题?

Example

1 个答案:

答案 0 :(得分:0)

首先-我们将简化示例:

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