首页 > 其他分享 >[Typescript] Handle Errors with a Generic Result Type

[Typescript] Handle Errors with a Generic Result Type

时间:2024-09-06 15:05:42浏览次数:5  
标签:Errors Handle success Generic data result error type Result

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.

标签:Errors,Handle,success,Generic,data,result,error,type,Result
From: https://www.cnblogs.com/Answer1215/p/18400245

相关文章

  • pymongo.errors.ConfigurationError: Server at localhost:27017 reports wire versio
    当你的PyMongo版本比较新时,如当前使用版本为v4.8.0,如果你尝试连接到MongoDBServerv3.4或更早版本,PyMongo可能会引发以下错误:pymongo.errors.ConfigurationError:Serveratlocalhost:27017reportswireversion5,butthisversionofPyMongorequiresatleast6(Mo......
  • 网站提示5xx Server Errors(服务器错误状态码)怎么办
    当遇到“5xxServerErrors”时,这意味着服务器在处理请求时遇到了错误,这些错误通常与服务器端的问题有关。5xx系列的状态码包括但不限于:500InternalServerError:服务器遇到了一个未曾预料的状况,导致它无法完成对请求的处理。501NotImplemented:服务器不支持请求的功能或API......
  • hyperf ValidationExceptionHandler
    <?phpdeclare(strict_types=1);/***ThisfileispartofHyperf.**@linkhttps://www.hyperf.io*@documenthttps://hyperf.wiki*@[email protected]*@licensehttps://github.com/hyperf/hyperf/blob/master/LICENSE*/namespaceApp......
  • Mybatis-Plus中的MetaObjectHandler
    简介MetaObjectHandler是一个非常有用的组件,用于处理实体对象中的字段填充逻辑,比如自动填充创建时间、更新时间、创建人、修改人等字段。组件介绍MetaObjectHandler接口允许在不修改业务代码的情况下,对实体类中的字段进行自动填充。这通常用于记录创建时间、更新时间、创建人......
  • devexpress gridview master,detail视图 focuseRowHandle 同步选中
    gridview1是主视图,gridview2是其子视图gridview1中的多行就对应了多个gridview2实例,那么通时展开多个gridview1中的多个行,并且在这些展开的行中点不同gridview2的行时,gridview1的焦点行是不会自动切换的的需要做如下处理(这里还包括了了gridview2中的checkboxedit)......
  • oem 软件更新 p9348486_112000_Generic,zip
    [oracle@prdb19oemtmp]$emclilogin-username=sysmanEnterpassword:Loginsuccessful[oracle@prdb19oemtmp]$emcliimport_update_catalog-file=p9348486_112000_Generic.zip-omslocalUnabletoreadthefilep9348486_112000_Generic.zip.Verifythefilep......
  • Spyglass cdc check报的errors
    1.report clocksignalsconvergingonamuxslave_adc是在mclk下进行同步,adc_bclk_i则是来自外部,因此切换bclk可能导致毛刺。可以通过切换之前先关闭后级的相关模块。 2.flagsaclocksinalwhosemulti-fanoutsconverge不太清楚要不要解决3.Ac_unsync01(3):Check......
  • Android开发 - Handler 类处理线程通信与任务调度解析
    什么是Handler类是处理线程间通信和任务调度的一个重要工具,用于在不同的线程之间传递消息和执行任务使用场景线程间通信:在子线程中执行任务后,更新主线程(UI线程)的界面。任务调度:安排在将来某个时间点执行的任务。基本工作原理消息队列:每个线程(包括主线程)都有一个......
  • mavn 执行 junit 单元测试的结果为 Tests run: 0, Failures: 0, Errors: 0, Skipped:
    mavn执行junit单元测试的结果为Testsrun:0,Failures:0,Errors:0,Skipped:0  [INFO]---surefire:3.2.5:test(default-test)@joyupx-trade---[INFO]Usingautodetectedproviderorg.apache.maven.surefire.junitplatform.JUnitPlatformProvider[INFO][INF......
  • TypeHandler时间数据类型的转换
    说明在Java开发中,TypeHandler是MyBatis框架中的一个核心组件,用于实现数据库与Java类型之间的相互转换。它允许开发人员自定义类型处理器,以满足特定的业务需求。TypeHandler的作用是在MyBatis执行SQL查询或更新操作时,将数据库中的列值转换为Java对象,并在将Java对......