如何将字符串转换为io-ts定义的联合类型,失败时抛出异常?
解决io-ts类型转换并在失败时抛出异常的方法
首先纠正一个小细节:你原代码里的type ExampleType = typeof Example是错误的,这会把类型定义成io-ts类型实例本身的类型,而非对应的值类型。正确的写法是用t.TypeOf<typeof Example>来获取值的类型。
下面是三种实现转换并在失败时抛异常的方法:
- 使用
assert方法(最简洁直接)
io-ts的类型实例自带assert方法,传入值不符合类型定义时会直接抛出Error:
import * as t from 'io-ts'; const Example = t.keyof({ 'foo': null, 'bar': null }); type ExampleType = t.TypeOf<typeof Example>; function convertToExample(value: string): ExampleType { Example.assert(value); return value; }
- 使用
decode结合fold自定义错误decode返回Either类型(左值为错误集合,右值为成功结果),通过fold可以分别处理两种情况,还能自定义错误信息:
import * as t from 'io-ts'; import { fold } from 'fp-ts/Either'; const Example = t.keyof({ 'foo': null, 'bar': null }); type ExampleType = t.TypeOf<typeof Example>; function convertToExample(value: string): ExampleType { return fold( (errors) => { throw new Error(`类型转换失败: ${t.errorsToJson(errors)}`); }, (result) => result )(Example.decode(value)); }
- 先判断再抛自定义异常
用is方法先检查值是否符合类型,不符合时抛出自定义提示的异常:
import * as t from 'io-ts'; const Example = t.keyof({ 'foo': null, 'bar': null }); type ExampleType = t.TypeOf<typeof Example>; function convertToExample(value: string): ExampleType { if (Example.is(value)) { return value; } throw new Error(`值"${value}"不是有效的Example类型,允许的值为'foo'、'bar'`); }
内容的提问来源于stack exchange,提问作者Abraham P
相关产品推荐
相关产品推荐

