[Typescript] Handle Errors with a Generic Result Type
Consider this Result
type:
type Result<TResult, TError> =
| {
success: true;
data: TResult;
}
| {
success: false;
error: TError;
};
The Result
type has two type parameters for TResult
and TError
.
It returns a discriminated union, with one branch indicating success and returning data, and the other pointing to failure and returning an error.
Next we have a createRandomNumber
function that returns a Result
type with a number
as the data and an Error
as the error:
const createRandomNumber = (): Result<number, Error> => {
const num = Math.random();
if (num > 0.5) {
return {
success: true,
data: 123,
};
}
return {
success: false,
error: new Error("Something went wrong"),
};
};
This function generates a random number and based on its value, renders a Result
type. If the number exceeds 0.5, it returns a successful result with some data. Otherwise, it returns a failure result with an error.
When we create a result
variable by calling createRandomNumber
, we can see that it is typed as Result
:
const result = createRandomNumber();
// hovering over result shows:
const result: Result<number, Error>
We in turn can conditionally check result.success
and obtain the correct type for result.data
. For example, if result.success
is true, then result.data
is typed as a number:
const result = createRandomNumber();
if (result.success) {
console.log(result.data);
type test = Expect<Equal<typeof result.data, number>>;
} else {
console.error(result.error);
type test = Expect<Equal<typeof result.error, Error>>;
}
This pattern proves very handy for error handling, as it eliminates the need for try-catch
blocks. Instead, we can directly check if the result was successful and act accordingly, or deal with the error.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2022-09-06 [Typescript Challenges] 16. Medium - Omit
2022-09-06 [Typescript Challenges] 15. Medium - Get return type of function
2022-09-06 [Go] Method
2022-09-06 [Go] Defer, panic, recover
2022-09-06 [Go] Error
2022-09-06 [GO] Pass by reference
2022-09-06 [Go] Pointer