javascript - 如何指示我们确定变量的值在 Typescript 中的数组中的变量和数组的类型?

标签 javascript reactjs arrays typescript react-native

你们知道以某种方式指示变量的类型吗?我们确信该变量的值位于 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

  1. 使用此语法告诉 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/

相关文章:

javascript - 在javascript中循环函数随机次数

javascript - -webkit-background-size 不适用于 jQuery Css

javascript - 意外的 token PropTypes

reactjs - 如何在自定义 Hook 中获取数据并将其分派(dispatch)到上下文

arrays - 将数组转换为 R 中的矩阵

javascript - 在正则表达式中转义撇号?

javascript - 位置粘性顶部和底部

javascript - 渲染前的 React 实例

javascript - 下面代码中的零指代什么

javascript - 在 Javascript 中轻松添加值数组(例如,没有循环)