[Typescript] Write clean Type 2 - Reduce the usage in generic slot
typescript in The type Write reduce Usage Clean
2023-09-14 09:00:42 时间
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.
相关文章
- 「使用 webpack 5 从0到1搭建React+TypeScript 项目环境」2. 集成 css、less 与 sass
- 「使用 webpack 5 从0到1搭建React + TypeScript 项目环境」3. 资源模块
- TypeScript-tsx文件webstorm无法识别alias配置解决方法
- typeScript:exports is not defined
- Java和TypeScript开发者之间的区别必须知道
- (十四)与 TypeScript 集成
- TypeScript入门
- ORA-32019: The parameter SPFILE cannot be updated in the server parameter file. ORACLE 报错 故障修复 远程处理
- ORA-48414: The string in the execution option exceeds maximum length [string] ORACLE 报错 故障修复 远程处理
- ORA-02324: more than one column in the SELECT list of THE subquery ORACLE 报错 故障修复 远程处理
- 硬核观察 | Python 之父对 Rust、Go、Julia 和 TypeScript 的看法
- MySQL 中的 IN 语句分析(mysql语句in)
- MySQL中的IN子句如何利用索引实现高效查询(mysql中in使用索引)
- MySQL中IN函数的使用及作用解析(mysql中in作用)
- 探究MySQL中IN表达式的作用及实际应用(mysql中in作用)
- 解决MySQL中IN不走索引问题的方法(mysql中in不走索引)
- Oracle中IN运算符的强大用法(oracle中in的使用)
- Oracle 中的 IN 子句使用技巧(oracle in 子句)