简体   繁体   中英

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?

Yes, you can use generic types, here is an example. The type of generic functions is just like those of non-generic functions, with the type parameters listed first, similarly to function declarations, you need to specify the type whenever you call the hook in different components, the type will infer in that way.

function identity<Type>(arg: Type): Type {
  return arg;
}
 
let myIdentity: <Type>(arg: Type) => Type = identity;

You can refer to this link for more information.

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>({...})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM