Javascript 异步回调的类型脚本定义
我有一个React钩子,用于获取数据:Javascript 异步回调的类型脚本定义,javascript,reactjs,typescript,asynchronous,callback,Javascript,Reactjs,Typescript,Asynchronous,Callback,我有一个React钩子,用于获取数据: const useData = (fetchingFn) => { const [data, setData] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) // ... handle loading data by calling `fechingFn()`, etc
const useData = (fetchingFn) => {
const [data, setData] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
// ... handle loading data by calling `fechingFn()`, etc
return {
data,
loading,
error
}
}
我正在尝试给它添加一些typescript酱汁,我有点挣扎,因为我对typescript有点陌生。如果有人能给我指出正确的方向,我愿意给你买块饼干
我为钩子的返回值添加了一个类型定义:
type UseDataReturnType = {
error: Error | null
loading: boolean
data: any | null
}
const useData = (fetchingFn: () => Promise<any>): UseDataReturnType => {
...
const fetchLoggedInUser = async (): Promise<User> => {
return db.get('users','bob'
}
const MyView = (): JSX.Element => {
const { loading, data, error } = useData(fetchLoggedInUserProfile)
// the data should be of type `User|null` here but instead, it is `any`
}
您可以使用泛型强烈地键入调用的返回类型。为此,您将必须传入承诺将解析到的类型,钩子将使用该类型并保存类型信息 这是传递类型信息的方式
// pass along the type info to the hook.
//** Usage when calling the hook **//
// The type is passed along in <>
const { loading, data, error } = useData<User>(fetchLoggedInUserProfile);
//** Hook Definition **//
// TData is the generic type. It can be named anything
// The promise is expected to return type that is passed in which is TData in the // definition, but User when the hook is used
// And lastly you pass in the captured type along to the return type, as the
// return type contains some additional meta info along with the original return type.
const useData = <TData>(fetchingFn: () => Promise<TData>): UseDataReturnType<TData> => {
}
//** Type consuming the generic **//
type UseDataReturnType<TData> = {
error: Error | null
loading: boolean
data: TData | null
}
//将类型信息传递给钩子。
//**调用钩子时的用法**//
//该类型在中传递
const{loading,data,error}=useData(fetchLoggedInUserProfile);
//**钩子定义**//
//TData是泛型类型。它可以被命名为任何东西
//promise应返回传入的类型,该类型在//定义中为TData,但在使用钩子时为User
//最后,将捕获的类型传递给返回类型,作为
//返回类型包含一些附加的元信息以及原始返回类型。
const useData=(fetchingFn:()=>Promise):UseDataReturnType=>{
}
//**使用泛型**//
类型UseDataReturnType={
错误:错误| null
加载:布尔值
数据:TData |空
}
您需要阅读typescript中的泛型-我非常确定在前面几个示例之后,您将能够实现您的目标。这非常有效。非常感谢,苏珊特!