首先,我们将简化示例:
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].
超型
进入
亚型
我们可以使用
$Shape
:
复制提供的类型的形状,但将每个字段标记为可选。
((anyObj: SuperType): $Shape<SubType>);
TLDR:
export type SearchContextType = {
dates: DateRange,
location: GoogleMapPosition,
update: ($Shape<{ dates?: DateRange, location?: GoogleMapPosition }>) => void
// ^ add `$Shape`
};
Corrected Example