reactjs - 对象类型中缺少流属性
问题描述
我有Props
一个组件的以下流类型:
type Props = {
// <...>
update: ({ dates?: DateRange }) => void
};
我还有以下导出类型:
export type SearchContextType = {
// <...>
update: ({ dates?: DateRange, location?: Location }) => void
};
当我尝试使用第二种类型将道具传递给第一个组件时,出现以下错误:
错误:(99, 23) 无法创建
MyComponent
元素,因为对象类型1location
中缺少属性,但在属性的第一个参数中存在于对象类型 [2] 中。update
我理解这个错误,但我的问题是:我怎样才能正确地绕过它?
解决方案
首先 - 我们将简化示例:
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`
};
推荐阅读
- javascript - 使用 node.js 中的数据库插件将文件添加到 heroku 应用程序
- sql - 从 Oracle 表中选择小时作为列
- python - 射线无休止地运行或只是不工作
- typescript - TypeScript 使用泛型有条件地合并道具类型
- android - FlatmapCompletable() 在 Single 上的不同行为
关于可完成的作文? - php - PDO 更新语句
- spring-boot - Spring OneToMany - 如何将对象列表限制为该对象的一个字段列表
- r - 如何根据两列找到唯一组合?
- c# - 如何在我的控制器文件中的 dot net 中获取用户名?
- reactjs - React Navigation v5:如何为自定义导航标题按钮编写导航路线?