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

如何读取typescript错误以了解应该使用什么类型?

  •  0
  • 1110  · 技术社区  · 2 年前

    我不明白如何处理这样的打字错误。
    我正在使用react导航,并尝试创建自定义标题。
    从文档中可以看到这个组件获得的参数列表,但我不知道如何进行类型检查。

    interface CustomHeaderProps {
      navigation: any;
      route: any;
      options: any;
      back: any;
    }
    
    const CustomHeader: FC<CustomHeaderProps> = ({
      navigation,
      route,
      options,
      back,
    }) => {...
    

    我在navigator中设置了标题:

    <HomeStack.Navigator
          screenOptions={{
            header: props => <CustomHeader {...props} />,
          }}>
    

    这里我得到了一个错误:

    (别名)const CustomHeader:React。常设费用 导入自定义标题 键入“{back?”:{title:string;}|未定义;选项:NativeStackNavigationOptions;路线:路线<字符串,对象| 未定义>;导航:NativeStackNavigationProp<ParamListBase, 字符串,未定义>;}'不可分配给类型“CustomHeaderProps”。 属性'back'在类型{back?:{title:string;}中是可选的未定义;选项:NativeStackNavigationOptions;路线: 路线<字符串,对象|未定义>;导航: NativeStackNavigationProp<ParamListBase,字符串,未定义>;}'但是 “CustomHeaderProps”类型中需要。

    有人能帮我理解这种错误,以及如何设置类型吗。

    1 回复  |  直到 2 年前
        1
  •  0
  •   0xe    2 年前

    错误的格式应如下所示:

    (alias) const CustomHeader: React.FC
    import CustomHeader
    Type '{ back?: { title: string; } | undefined; options: NativeStackNavigationOptions; route: Route<string, object | undefined>; navigation: NativeStackNavigationProp<ParamListBase, string, undefined>; }' is not assignable to type 'CustomHeaderProps'.
        Property 'back' is optional in type '{ back?: { title: string; } | undefined; options: NativeStackNavigationOptions; route: Route<string, object | undefined>; navigation: NativeStackNavigationProp<ParamListBase, string, undefined>; }' but required in type 'CustomHeaderProps'.
    

    通常他们总是这样:

    Offending code
    Type '...' is not assignable to type '...'
        Reason why it isn't
            Reason why the reason is why
                Reason why the reason why the reason is why
                    ...
    

    原因很简单 Property 'back' is not optional in type '...' but required in type '...' 。大多数情况下,真正的原因是最后一个,帮助最大,但在更详细的错误中,你应该去“原因堆栈”查找根本原因。

    所以对于实际错误,它抱怨属性在 props 你给了,但它不在定义中。

    (并非所有类型脚本错误都是这种格式。只有这类类型不匹配错误是这样的。)