Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing types as arguments in Typescript

i've written a custom hook to help me not repeat code for some fetch calls. it looks like this:

export const useCustomQuery = ({ endpoint, body, dataPoint }: args) => {
    const [data, setData] = useState()
    useEffect(() => {
        fetch(`http://localhost:4000/${endpoint}`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body,
        })
            .then((res) => res.json())
            .then((res) => {
                if (dataPoint) {
                    setData(JSON.parse(res.data[dataPoint]))
                }
            })
    }, [endpoint, body, dataPoint])

    return { data }
}

but I'm getting some TS errors complaining about the type of data. is it possible to pass in the type as an argument as it might be different for each component that calls the hook? or what is the best way to approach this?

like image 806
Red Baron Avatar asked Mar 08 '26 19:03

Red Baron


1 Answers

You can use generic in this case. You can do something like this:

export const useCustomQuery = <T,>({ endpoint, body, dataPoint }: args) => {
    const [data, setData] = useState<T>()
    ...
}

This way, you are giving a type T when you call the hook useCustomQuery, that parameterized the type of data, like this:

useCustomQuery<MyType>({...})
like image 50
TheTisiboth Avatar answered Mar 11 '26 08:03

TheTisiboth