[Typescript] Handling conditional return type of a function

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

function youSayGoodbyeISayHello(greeting: unknown) {
  return greeting === "goodbye" ? "hello" : "goodbye";
}

it("Should return goodbye when hello is passed in", () => {
  const result = youSayGoodbyeISayHello("hello");

  type test = [Expect<Equal<typeof result, "goodbye">>];

  expect(result).toEqual("goodbye");
});

it("Should return hello when goodbye is passed in", () => {
  const result = youSayGoodbyeISayHello("goodbye");

  type test = [Expect<Equal<typeof result, "hello">>];

  expect(result).toEqual("hello");
});

So in the function `youSayGoodbyISayHello`, we want both runtime and compile time type safety. The the return type of the function should either be `hello` or `goodbye` based on the input params is `goodbye` or `hello`.

 

Solution 1: using () as any

function youSayGoodbyeISayHello<T extends 'goodbye' | 'hello'>(
  greeting: T
): T extends 'goodbye' ? 'hello' : 'goodbye' {
  return (greeting === 'goodbye' ? 'hello' : 'goodbye') as any;
}

The idea is typescript is not smart enough to know greeting === 'goodbye' ? 'hello' : 'goodbyethe return type is string `goodbye` or `hello`, therefore you need to use as anyjust let typescript know, you know exactly what return type it is.

 

Solution 2: as GreetingReturnType<T>

type GreetingReturnType<T extends 'goodbye' | 'hello'> = T extends 'goodbye'
  ? 'hello'
  : 'goodbye';

function youSayGoodbyeISayHello<T extends 'goodbye' | 'hello'>(greeting: T) {
  return (
    greeting === 'goodbye' ? 'hello' : 'goodbye'
  ) as GreetingReturnType<T>;
}

 

----

The same as this one:

type Person = {
  name: string;
  age: number;
  birthdate: Date;
};

export function remapPerson<Key extends keyof Person>(
  key: Key,
  value: Person[Key]
): Person[Key] {
  if (key === 'birthdate') {
    return new Date() as Person[Key]; // return new Date() as any
  }

  return value;
}

 

posted @   Zhentiw  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-01-27 [Yarn] Use yarn up to Update Dependencies In A Yarn Workspace
2020-01-27 [Yarn] Use Yarn dlx to Execute Packages without Installing Them
2020-01-27 [Yarn] Install Yarn2
2020-01-27 [Tools] Install npm packages globally without sudo on macOS and Linux
2019-01-27 [TypeScript] Dynamically initialize class properties using TypeScript decorators
2016-01-27 [Javascript] Web APIs: Persisting browser data with window.localStorage
2016-01-27 [Javascript] The JSON.stringify API
点击右上角即可分享
微信分享提示