Reactjs 对象类型中缺少流属性
我有以下组件的流程Reactjs 对象类型中缺少流属性,reactjs,flowtype,Reactjs,Flowtype,我有以下组件的流程Props类型: type Props = { // <...> update: ({ dates?: DateRange }) => void }; 类型道具={ // 更新:({dates?:DateRange})=>void }; 我还有以下导出类型: export type SearchContextType = { // <...> update: ({ dates?: DateRange, location?: L
Props
类型:
type Props = {
// <...>
update: ({ dates?: DateRange }) => void
};
类型道具={
//
更新:({dates?:DateRange})=>void
};
我还有以下导出类型:
export type SearchContextType = {
// <...>
update: ({ dates?: DateRange, location?: Location }) => void
};
导出类型SearchContextType={
//
更新:({dates?:DateRange,location?:location})=>void
};
当我尝试使用第二种类型将道具传递给第一个组件时,会出现以下错误:
错误:(99,23)无法创建MyComponent
元素,因为属性location
在对象类型中缺失,但在属性update
的第一个参数的对象类型[2]中存在
我理解这个错误,但我的问题是:我如何才能正确地避开它
首先-我们将简化示例:
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.
或者我们可以说我们将超类型
转换为子类型
((anyObj: SuperType): SubType);
// ^ Cannot cast `anyObj` to `SubType` because property `location` is missing in `SuperType` [1] but exists in `SubType` [2].
要将超类型
转换为子类型
,我们可以使用$Shape
:
复制提供的类型的形状,但将每个字段标记为可选
//正确
((anyObj:超类型):$Shape);
TLDR:
export type SearchContextType = {
dates: DateRange,
location: GoogleMapPosition,
update: ($Shape<{ dates?: DateRange, location?: GoogleMapPosition }>) => void
// ^ add `$Shape`
};
导出类型SearchContextType={
日期:日期范围,
地点:谷歌地图位置,
更新:($Shape)=>void
//^添加“$Shape”`
};
也许您应该在使用类型的地方共享实际代码?我已经设置了Flow try repo,无法重现您的问题,请随意编辑,不要忘记选择您的Flow版本:
export type SearchContextType = {
dates: DateRange,
location: GoogleMapPosition,
update: ($Shape<{ dates?: DateRange, location?: GoogleMapPosition }>) => void
// ^ add `$Shape`
};