你们知道以某种方式指示变量的类型吗?我们确信该变量的值位于 Typescript 的数组中?
例如,我想在选项卡栏上显示选项卡列表:
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])
...
}
并且在选项卡具有这种形式 {id:number;title:string}
的情况下,如何使 tabs.find(tab => tab.id === activeTab.id)
没有错误?
谢谢!!!
最佳答案
您的具体问题与数组可能为空这一事实有关,为了使 Typescript 像您一样,请执行以下两件事:
假设您的类型是 Tab
,也可以是 string
。
- 使用此语法告诉 typescript 数组中至少有一个元素。
const TabsBar = ({ tabs }: { tabs: [Tab, ...Tab[]] }) => {
// implementation
}
2.处理find
返回未定义的情况。
...
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)
}
关于javascript - 如何指示我们确定变量的值在 Typescript 中的数组中的变量和数组的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77488887/