首页 > 其他分享 >[Typescript] Use Function Overloads to Avoid Returning undefined

[Typescript] Use Function Overloads to Avoid Returning undefined

时间:2023-02-08 14:36:53浏览次数:38  
标签:Function Use Typescript undefined initialData params fetchData getData data

// 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,
  };
}

 

标签:Function,Use,Typescript,undefined,initialData,params,fetchData,getData,data
From: https://www.cnblogs.com/Answer1215/p/17101621.html

相关文章