[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' : 'goodbye
the return type is string `goodbye` or `hello`, therefore you need to use as any
just 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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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