[Typescript] Use Function Overloads to Avoid Returning undefined
// You'll need to use function overloads to figure this out!
function useData<T>(params: { fetchData: () => Promise<T>; initialData?: T }): {
getData: () => T | undefined;
} {
let data = params.initialData;
params.fetchData().then((d) => {
data = d;
});
return {
getData: () => data,
};
}
When we calling the function like this:
const numData = useData({
fetchData: () => Promise.resolve(1),
});
const data = numData.getData();
// ^? number | undefined
And:
const numData = useData({
fetchData: () => Promise.resolve(1),
initialData: 2,
});
const data = numData.getData();
// ^? number | undefined
In fact, in second code example, the return data won't be undefined, because we pass in initialData
. We need to find a way to make type better
Solution:
Two cases:
1. Without initialData
, should return T | undefined
2. With initialData
, should return T
function useData<T>(params: { fetchData: () => Promise<T>;}): {
getData: () => T | undefined;
};
function useData<T>(params: { fetchData: () => Promise<T>; initialData: T }): {
getData: () => T;
};
function useData<T>(params: { fetchData: () => Promise<T>; initialData?: T }): {
getData: () => T | undefined;
} {
let data = params.initialData;
params.fetchData().then((d) => {
data = d;
});
return {
getData: () => data,
};
}