[Typescript] Write clean Type 2 - Reduce the usage in generic slot
This the following code example, test have passed for both run time and compile time:
import { expect, it } from 'vitest';
import { Equal, Expect } from '../helpers/type-utils';
function youSayGoodbyeISayHello<
T extends 'hello' | 'goodbye',
RES = T extends 'hello' ? 'goodbye' : T extends 'goodbye' ? 'hello' : T
>(greeting: T) {
return (greeting === 'goodbye' ? 'hello' : 'goodbye') as RES;
}
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');
});
Something we want to improve in the type level:
We use RES
in generic slot, it is just for the return type.
We can also use another approach which might be cleaner.
type GreetingType<T extends 'hello' | 'goodbye'> = T extends 'hello'
? 'goodbye'
: T extends 'goodbye'
? 'hello'
: T;
function youSayGoodbyeISayHello<T extends 'hello' | 'goodbye'>(greeting: T) {
return (greeting === 'goodbye' ? 'hello' : 'goodbye') as GreetingType<T>;
}
In this version, we have only one genric slot, which looks cleaner.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2022-04-11 [React] Directly Dispatch Actions into the Redux Store Before React Renders
2022-04-11 [Javascript] Extending debounce with a maxWait Option
2022-04-11 [Javascript] Build lodash.debounce from Scratch
2022-04-11 [Javascript] Build lodash.merge from Scratch
2020-04-11 [RxJS] Extend Promises by Adding Custom Behavior
2019-04-11 [Algorithm] Binary tree: Level Order Traversal
2019-04-11 [SSH] Intro to SSH command