[英]How can I properly set a type for `useState`, if I want the piece of state to either be an object or null?
[英]How can I properly type this?
我有這個 React 組件:
const Icon = ({ icon, ...props }: { icon: keyof IconType }) => {
const Icon = Icons[icon]
return <Icon {...props} />
}
我試圖以這種方式使用它:
<Icon icon={ordinaryString} />
我怎樣才能避免收到此打字稿錯誤:
The type "string" cannot be assigned to the type "keyof IconType".
我將假設ordinaryString
string
是string
類型,因為這就是錯誤消息所說的。
問題是您要提供一個字符串,它可以是任何東西,但組件需要keyof IconType
,它不能只是任何字符串,而必須是與IconType
中的鍵之一匹配的字符串。
要么提供與keyof IconType
匹配的字符串文字(或使用keyof IconType
鍵入的變量/常量),將組件中icon
道具的類型更改為string
(但請注意,后一個選項將意味着Icons
需要可通過字符串索引)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.