首页 > 解决方案 > 对象类型中缺少流属性

问题描述

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

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

我还有以下导出类型:

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

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

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

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

例子

标签: reactjsflowtype

解决方案


首先 - 我们将简化示例:

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.
}

换句话说,我们只是使用类型转换来转换FooBar

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.

或者我们可以说我们转换SuperTypeSubType

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

要转换SuperTypeSubType我们可以使用$Shape

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

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

TLDR:

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

更正示例


推荐阅读