Props我的组件有以下流类型:
type Props = {
// <...>
update: ({ dates?: DateRange }) => void
};
Run Code Online (Sandbox Code Playgroud)
我还有以下导出类型:
export type SearchContextType = {
// <...>
update: ({ dates?: DateRange, location?: Location }) => void
};
Run Code Online (Sandbox Code Playgroud)
当我尝试使用第二种类型将道具传递给第一个组件时,出现以下错误:
错误:(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.
}
Run Code Online (Sandbox Code Playgroud)
换句话说,我们只是使用类型转换来转换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.
Run Code Online (Sandbox Code Playgroud)
或者我们可以说我们转换SuperType成SubType
((anyObj: SuperType): SubType);
// ^ Cannot cast `anyObj` to `SubType` because property `location` is missing in `SuperType` [1] but exists in `SubType` [2].
Run Code Online (Sandbox Code Playgroud)
要转换SuperType为SubType我们可以使用$Shape:
复制提供的类型的形状,但将每个字段标记为可选。
// Correct
((anyObj: SuperType): $Shape<SubType>);
Run Code Online (Sandbox Code Playgroud)
总而言之:
export type SearchContextType = {
dates: DateRange,
location: GoogleMapPosition,
update: ($Shape<{ dates?: DateRange, location?: GoogleMapPosition }>) => void
// ^ add `$Shape`
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9482 次 |
| 最近记录: |