代码之家  ›  专栏  ›  技术社区  ›  Sammy

对象类型中缺少流属性

  •  3
  • Sammy  · 技术社区  · 6 年前

    我有以下流程 Props 组件的类型:

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

    我还有以下导出类型:

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

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

    错误:(99,23)无法创建 MyComponent location 对象类型中缺少 1 但存在于属性的第一个参数的对象类型[2]中 update .

    我理解这个错误,但我的问题是:我如何才能正确地避开它?

    Example

    1 回复  |  直到 6 年前
        1
  •  0
  •   Buggy    6 年前

    首先,我们将简化示例:

    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 :

    复制提供的类型的形状,但将每个字段标记为可选。

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

    TLDR:

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

    Corrected Example