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!!!
3
Answers
You can use TypeScript generics to define the types of the
tabs
array and theactiveTab
state and theas
keyword to assert that the result offind
won’t beundefined
.If you do so :
Then, it should be ok, although, it doesn’t exactly reply to your request.
Otherwise, you would have to put an exclamation mark (non-null assertion operator) here :
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 bestring
as well.2.handle the case in which
find
returns undefined.