[Typescript] Function overload: Data hook problem

Requirement is if pass in initialData, then return type should not contain undefined, otherwise, it should.

import { it } from "vitest";
import { Equal, Expect } from "../helpers/type-utils";

// You'll need to use function overloads to figure this out!
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,
  };
}

it("Should return undefined if no initial data is passed", () => {
  const numData = useData({
    fetchData: () => Promise.resolve(1),
  });

  const data = numData.getData();

  type Test1 = Expect<Equal<typeof data, number | undefined>>;
});

it("Should NOT return undefined if initial data is passed", () => {
  const numData = useData({
    fetchData: () => Promise.resolve(1),
    initialData: 2,
  });

  const data = numData.getData();

  type Test1 = Expect<Equal<typeof data, number>>;
});

 

posted @   Zhentiw  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-02-02 [AWS] AWS Control Tower for multi accounts
2018-02-02 [Typescript] Build Method decorators in Typescript
2017-02-02 [Javascript] Write a function pipeline
2017-02-02 [React] Pass Data To Event Handlers with Partial Function Application
2016-02-02 [Cycle.js] Read effects from the DOM: click events
2016-02-02 [Cycle.js] Introducing run() and driver functions
2016-02-02 [Cycle.js] Customizing effects from the main function
点击右上角即可分享
微信分享提示