[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.

posted @   Zhentiw  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源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
点击右上角即可分享
微信分享提示