gpt4 book ai didi

reactjs - 对象类型中缺少流属性

转载 作者:行者123 更新时间:2023-12-03 14:31:33 38 4
gpt4 key购买 nike

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

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

我还有以下导出类型:

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

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

Error:(99, 23) Cannot create MyComponent element because property location is missing in object type 1 but exists in object type [2] in the first argument of property update.

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

Example

最佳答案

首先 - 我们将简化示例:

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:

Copies the shape of the type supplied, but marks every field optional.

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

TLDR:

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

Corrected Example

关于reactjs - 对象类型中缺少流属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51231324/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com