I was trying to build a generic service to load from an endpoint. It works, but I would like to use
const useService = <T>(endpoint: string) => {...}
but it doesn't work. Is it possible to type a function with this syntax, or sugar?
export interface ISubscription<T> {
payload: T[];
}
type Service<T> = Service<ISubscription<T>>;
const useService = function<T>(endpoint: string) {
const [result, setResult] = useState<Service<T>>({
status: 'loading'
});
useEffect(() => {
API.axiosClient.get<ISubscription<T>>(`xxx/${endpoint}`)
.then(response => {
setResult({ status: 'loaded', payload: { payload: response.data.payload } });
})
.catch(error => setResult({ status: 'error', error }));
}, [endpoint]);
return result;
};
where Service
is
interface ServiceInit {
status: 'init';
}
interface ServiceLoading {
status: 'loading';
}
export interface ServiceLoaded<T> {
status: 'loaded';
payload: T;
}
interface ServiceError {
status: 'error';
error: Error;
}
export type Service<T> =
| ServiceInit
| ServiceLoading
| ServiceLoaded<T>
| ServiceError;