reactjs 对象类型中缺少流属性

ldioqlga  于 2023-03-08  发布在  React
关注(0)|答案(1)|浏览(115)

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

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

我还有以下导出类型:

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

当我尝试使用第二种类型将 prop 传递给第一个组件时,我得到了以下错误:
错误:(99,23)无法创建MyComponent元素,因为对象类型1中缺少属性location,但对象类型[2]中存在属性update的第一个参数。
我知道你搞错了,但我的问题是:我怎样才能正确地绕过它呢?
示例

tkclm6bt

tkclm6bt1#

首先,我们将简化示例:

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>);

顶级域名:

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

纠正示例

相关问题