reactjs 在Typescript中,如何表示变量和数组的类型,我们可以确定变量的值在数组中?

tv6aics1  于 2023-11-18  发布在  React
关注(0)|答案(3)|浏览(142)

你们知道用什么方法来表示一个变量的类型吗,我们可以确定这个变量的值在Typescript中的一个数组中?
对于Puple,我想在标签栏上显示一个标签列表:

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)没有错误?
谢谢你!

uyto3xhc

uyto3xhc1#

你的具体问题与数组可能为空的事实有关,为了让Typescript像你一样,做两件事:
假设Tab是你的类型,也可能是string
1.使用此语法告诉typescript数组中至少有一个元素。

const TabsBar = ({ tabs }: { tabs: [Tab, ...Tab[]] }) => {
      // implementation
   }

字符串
2.处理find返回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)
   }

ccgok5k5

ccgok5k52#

您可以使用TypeScript泛型来定义tabs数组和activeTab状态的类型,以及as关键字来Assertfind的结果不会是undefined

import { useState, useEffect } from 'react';

// Define a generic type for tabs that can be either string or an object with an `id` property
type Tab = string | { id: number; title: string };

const TabsBar = ({ tabs }: { tabs: Tab[] }) => {
    const [activeTab, setActiveTab] = useState<Tab>(tabs[0]);

    useEffect(() => {
        // Check if activeTab is a string or an object with an `id` property
        if (typeof activeTab === 'string') {
            // For string tabs, find the tab by directly comparing values
            setActiveTab(tabs.find(tab => tab === activeTab) as Tab);
        } else {
            // For object tabs, find the tab by matching the `id` property
            setActiveTab(tabs.find(tab => (tab as { id: number }).id === (activeTab as { id: number }).id) as Tab);
        }
    }, [tabs, activeTab]);

    // Rest of your component...

    return (
        <div>
            {/* Render your tabs here */}
        </div>
    );
};

export default TabsBar;

字符串

7vhp5slm

7vhp5slm3#

如果您这样做:

const TabsBar= ({tabs}: {tabs: string[]}) => {
  const [activeTab, setActiveTab] = useState<string>(tabs[0]) 
  useEffect(() => {
    const result = tabs.find(tab => tab === activeTab);
    if (result) {setActiveTab(result))};
    }, [tabs, activeTab])
}

字符串
那么,应该没问题,虽然,它并没有完全回复你的请求。
否则,你必须在这里放一个感叹号(非空Assert运算符):

tabs.find(tab => tab === activeTab)!

相关问题