[Typescript] Write clean Type 1 - Generic slots, using built-in types as much as possible
typescript in type Using as Write types Clean
2023-09-14 08:59:11 时间
There are two options doing the same things.
const makeSafe =
<TParams extends any[], TReturn>(func: (...args: TParams) => TReturn) =>
(
...args: TParams
):
| {
type: "success";
result: TReturn;
}
| {
type: "failure";
error: Error;
} => {
try {
const result = func(...args);
return {
type: "success",
result,
};
} catch (e) {
return {
type: "failure",
error: e as Error,
};
}
};
Option2:
const makeSafe =
<TFunc extends (...args: any[]) => any>(func: TFunc) =>
(
...args: Parameters<TFunc>
):
| {
type: "success";
result: ReturnType<TFunc>;
}
| {
type: "failure";
error: Error;
} => {
try {
const result = func(...args);
return {
type: "success",
result,
};
} catch (e) {
return {
type: "failure",
error: e as Error,
};
}
};
Both options provide a similar implementation for the makeSafe
function, but they differ in their typing. Option 2 is more concise and considered better because it uses built-in TypeScript utility types Parameters
and ReturnType
to infer the argument types and return type of the given function func
. This makes the code easier to read and understand.
I recommend going with Option 2 for its cleaner and more concise typing.
相关文章
- typescript快速入门
- 快速搭建基于Vue3+Vite2+Arco+Typescript+Pinia后台管理系统模板,文末有福利
- 【工程搭建】从零搭建一个 typescript + express + eslint 工程
- 类型体操:探究 TypeScript 内置高级类型
- 初识 TypeScript
- TypeScript笔记
- TypeScript 中 as const 是什么
- TypeScript 4.8 发布!重点新特性解读
- 开心档之TypeScript 变量声明
- TypeScript实例_手动编译与自动编译、类型注解、接口和类的详解
- Node.js脚手架开发完全指南「TypeScript版」
- ORA-22319: type attribute information altered in ALTER TYPE ORACLE 报错 故障修复 远程处理
- 提升Oracle中IN操作的效率(oracle的in效率)
- 运算MySQL无法使用IN操作(mysql不能用in)
- 查询MySQL使用IN查询实现复杂搜索(mysql条件in)
- 和existsMySQL首选:少用IN和EXISTS方法(mysql少用in)
- 微软为大型 JavaScript 应用而开发的 TypeScript 发布了 2.0 版本
- 利用Oracle中IN运算符的优势(oracle中in的作用)
- 如何有效运用SQL Server的IN语句(sqlserver用in)
- MySQL中的Out和In操作一个简单的指南(mysql中out 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的详解)
- 使用Oracle中的IN条件实现复杂查询(oracle中in条件)
- 查询Oracle中使用IN关键字查询多个值的方法(oracle中in多个值)
- Oracle中IN与OR运算实现多条件查询的最佳选择(oracle中in与or)
- Oracle IN查询双重优势一步搞定复杂任务(oracle两个in查询)