Issue
Do you guys know somehow to indicate type of a variable we know for sure that the value of this variable is in an array in Typescript?
For exemple, I want to display a list of tabs on a tabs bar:
const TabsBar= ({tabs}: {tabs: string[]}) => {
const [activeTab, setActiveTab] = useState<string>(tabs[0]) //the active tab by default is the first tab in array of tabs
useEffect(() => {
setActiveTab(tabs.find(tab => tab === activeTab))//give error Argument of type 'string | undefined' is not assignable
//to parameter of type 'string'. How to define type of "tabs" and "activeTab" so that the error disappear?
}, [tabs, activeTab])
...
}
And also in the case that a tab has this form {id:number;title:string}
, how to make tabs.find(tab => tab.id === activeTab.id)
without error?
Thank you!!!
Solution
Your specific problems are related to the fact that arrays might be empty, in order to make Typescript like you, do 2 things:
let's say Tab
is your type, could be string
as well.
- use this syntax to tell typescript that there's at least one element in the array.
const TabsBar = ({ tabs }: { tabs: [Tab, ...Tab[]] }) => {
// implementation
}
2.handle the case in which find
returns undefined.
...
useEffect(() => {
const selected = tabs.find(...) //now selected is of type `Tab | undefined`
if (!selected) throw Error("Unexpected tab") // this shouldn't happen
// any future usage of `selected` would be Tab without undefined
setActiveTab(selected)
}
Answered By - Mr. Nun.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.