Home > Back-end >  Narrow union types for custom react hook
Narrow union types for custom react hook

Time:04-03

I have 4 objects with few similar keys & a few different keys. I am using their union for database operations like so ->

type Objects = Food | Diary | Plan | Recipe ;

Pagination custom hook

function usePaginate (key: string, options: Options) {
    const [data,setData] = useState<Objects[]>([]);
    const perPage = 10;
    const [first, setFirst] = useState(0);
    const [last, setLast] = useState(perPage);

    const links = () => data.slice(first,last);

    function paginate(clicked: 'next' | 'previous') {
        if(clicked === 'next' && data.length > (first perPage)) {
            setFirst(first perPage);
            setLast(last perPage);
        }
        if(clicked === 'previous' && (first-perPage) >= 0) {
            setFirst(first-perPage);
            setLast(last-perPage);
        }
    }

    useEffect(()=>{
        setData(getData(key,options));
    },[])

    return [links(),paginate] as const;
}

Calling custom hook in StockDisplay component

const StockDisplay = () => {
    const [foods, paginate] = usePaginate('foods',{'sort':['-stocked','info.name']});
    return (<>{foods.map(food => <Stock data={food} key={food.id} />)}</>)
    // I have also tried adding a check like below but the error persists. 'stocked' is a key that only exists in Food type
    return (<>{('stocked' in foods) && foods.map(food => <Stock data={food} key={food.id} />)}</>)
}

At this point, foods' type is const foods: Objects[] & paginate's type is const paginate: (clicked: "next" | "previous") => void. But the return line throws this error ->

Type 'Objects' is not assignable to type 'Food'.ts(2322)
Stock.tsx(12, 26): The expected type comes from property 'data' which is declared here on type 'IntrinsicAttributes & { data: Food; }'

This is because in the Stock component below, data is defined to be the type Food but in the above StockDisplay component, I'm receiving Objects[].

Stock component

const Stock = ({data} : {data: Food}) => {
     return (
          <></>
     )
}

My question is, How do I narrow down Objects[] output from the hook to just Food[] in StockDisplay component ?

CodePudding user response:

1. Quick workaround using type casting

const StockDisplay = () => {
    const [foods, paginate] = usePaginate('foods',{'sort':['-stocked','info.name']});
    return (<>{(foods as Food[]).map(food => <Stock data={food} key={food.id} />)}</>)
    // I have also tried adding a check like below but the error persists. 'stocked' is a key that only exists in Food type
    return (<>{('stocked' in foods) && foods.map(food => <Stock data={food} key={food.id} />)}</>)
}

2. Using generics

function usePaginate<T>(key: string, options: Options): readonly [T[], (clicked: 'next' | 'previous') => void] {
    const [data,setData] = useState<Objects[]>([]);
    const perPage = 10;
    const [first, setFirst] = useState(0);
    const [last, setLast] = useState(perPage);

    const links = () => data.slice(first,last);

    function paginate(clicked: 'next' | 'previous') {
        if(clicked === 'next' && data.length > (first perPage)) {
            setFirst(first perPage);
            setLast(last perPage);
        }
        if(clicked === 'previous' && (first-perPage) >= 0) {
            setFirst(first-perPage);
            setLast(last-perPage);
        }
    }

    useEffect(()=>{
        setData(getData(key,options));
    },[])

    return [links(),paginate] as const;
}
const StockDisplay = () => {
    const [foods, paginate] = usePaginate<Food>('foods',{'sort':['-stocked','info.name']});
    return (<>{foods.map(food => <Stock data={food} key={food.id} />)}</>)
    // I have also tried adding a check like below but the error persists. 'stocked' is a key that only exists in Food type
    return (<>{('stocked' in foods) && foods.map(food => <Stock data={food} key={food.id} />)}</>)
}
  • Related