在 Typescript 中将类型作为参数传递

Red*_*ron 4 javascript typescript reactjs react-hooks react-custom-hooks

我编写了一个自定义挂钩来帮助我不重复某些获取调用的代码。它看起来像这样:

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 }
}
Run Code Online (Sandbox Code Playgroud)

但我收到一些 TS 错误,抱怨数据类型。是否可以将类型作为参数传递,因为调用钩子的每个组件可能会有所不同?或者解决这个问题的最佳方法是什么?

The*_*oth 8

在这种情况下您可以使用泛型。你可以这样做:

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

这样,当您调用钩子时,您将给出一个类型 T useCustomQuery,该钩子参数化了 的类型data,如下所示:

useCustomQuery<MyType>({...})
Run Code Online (Sandbox Code Playgroud)