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

 

posted @   Zhentiw  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-02-08 [JS Pattern] Mixin Pattern
2021-02-08 [Bash] Understand Exit Statuses in Bash
2021-02-08 [Bash] Chmod
2021-02-08 [Bash] Create and Run Bash Scripts with Command Line Arguments
2021-02-08 [Bash] Operations against Folder
2021-02-08 [Bash] Operations against files
2019-02-08 [Functional Programming ADT] Debug a Functional JavaScript composeK Flow
点击右上角即可分享
微信分享提示