簡體   English   中英

如何閱讀 typescript 錯誤以了解應使用哪種類型?

[英]How to read typescript error in order to understand what type should be used?

我不明白如何處理這樣的 typescript 錯誤。
我正在使用 react-navigation 並嘗試自定義 header。
從文檔中有該組件獲取的參數列表,但我不知道如何鍵入檢查它。

interface CustomHeaderProps {
  navigation: any;
  route: any;
  options: any;
  back: any;
}

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

我在導航器中設置了 header:

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

在這里我得到錯誤:

(別名)const CustomHeader: React.FC import CustomHeader Type '{ back?: { title: string; } | 不明確的; 選項:NativeStackNavigationOptions; 路線:路線<字符串,object | 未定義>; 導航:NativeStackNavigationProp<ParamListBase, string, undefined>; }' 不可分配給類型 'CustomHeaderProps'。 屬性 'back' 在類型 '{ back?: { title: string; 中是可選的 } | 不明確的; 選項:NativeStackNavigationOptions; 路線:路線<字符串,object | 未定義>; 導航:NativeStackNavigationProp<ParamListBase, string, undefined>; }' 但在類型 'CustomHeaderProps' 中是必需的。

有人可以幫助我如何理解這種關閉錯誤以及如何設置類型。

錯誤應該已經格式化如下:

(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 '...' 大多數時候,真正的原因排在最后並且幫助最大,但在更詳細的錯誤中,您應該 go 向上“原因堆棧”找出根本原因。

因此,對於實際錯誤,它抱怨該屬性在您提供的props類型中是可選的,但它不在定義中。

(不是所有的TypeScript錯誤都是這種格式,只有這幾種類型不匹配錯誤是這樣的。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM