使用不可构造类型的 TypeScript 中的丰富编译时异常
来源:dev.to
时间:2024-10-30 08:19:01 208浏览 收藏
来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习文章相关编程知识。下面本篇文章就来带大家聊聊《使用不可构造类型的 TypeScript 中的丰富编译时异常》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!
typescript 的类型系统很强大,但它的错误消息有时可能很神秘且难以理解。在本文中,我们将探索一种使用不可构造类型来创建清晰的、描述性的编译时异常的模式。这种方法通过使无效状态无法用有用的错误消息来表示来帮助防止运行时错误。
模式:具有自定义消息的不可构造类型
首先,我们来分解一下核心模式:
// create a unique symbol for our type exception declare const typeexception: unique symbol; // basic type definitions type struct = record; type funct = (arg: t) => r; type types = keyof t & string; type sanitize = t extends string ? t : never; // the core pattern for type-level exceptions export type unbox = { [type in types ]: t[type] extends funct ? (arg: ret) => any : t[type] extends struct ? { [typeexception]: `variant <${sanitize }> is of type . migrate logic to variant to capture <${sanitize }> types.`; } : (value: t[type]) => any; };
它是如何运作的
- typeexception 是一个独特的符号,充当我们错误消息的特殊键
- 当我们遇到无效类型状态时,我们返回一个带有 typeexception 属性的对象类型
- 此类型在运行时不可构造,迫使 typescript 显示我们的自定义错误消息
- 错误消息可以包含使用模板文字的类型信息
示例 1:带有自定义错误的变体处理
以下示例展示了如何将此模式与变体类型一起使用:
type datavariant = | { type: 'text'; content: string } | { type: 'number'; value: number } | { type: 'complex'; nested: { data: string } }; type varianthandler = unbox<{ text: (content: string) => void; number: (value: number) => void; complex: { // this will trigger our custom error [typeexception]: `variantis of type . migrate logic to variant to capture types.` }; }>; // this will show our custom error at compile time const invalidhandler: varianthandler = { text: (content) => console.log(content), number: (value) => console.log(value), complex: (nested) => console.log(nested) // error: type has unconstructable signature };
示例 2:递归类型验证
这是一个更复杂的示例,展示了如何将模式与递归类型一起使用:
type treenode= { value: t; children?: treenode []; }; type treehandler = unbox<{ leaf: (value: t) => void; node: treenode extends struct ? { [typeexception]: `cannot directly handle node type. use leaf handler for individual values.`; } : never; }>; // usage example - will show custom error const invalidtreehandler: treehandler = { leaf: (value) => console.log(value), node: (node) => console.log(node) // error: cannot directly handle node type };
示例 3:类型状态验证
以下是我们如何使用该模式来强制执行有效的类型状态转换:
type loadingstate= { idle: null; loading: null; error: error; success: t; }; type statehandler = unbox<{ idle: () => void; loading: () => void; error: (error: error) => void; success: (data: t) => void; // prevent direct access to state object state: loadingstate extends struct ? { [typeexception]: `cannot access state directly. use individual handlers for each state.`; } : never; }>; // this will trigger our custom error const invalidstatehandler: statehandler = { idle: () => {}, loading: () => {}, error: (e) => console.error(e), success: (data) => console.log(data), state: (state) => {} // error: cannot access state directly };
何时使用此模式
此模式在以下情况下特别有用:
- 您需要在编译时阻止某些类型组合
- 您希望针对类型违规提供清晰的描述性错误消息
- 您正在构建复杂的类型层次结构,其中某些操作应受到限制
- 您需要通过有用的错误消息引导开发人员采用正确的使用模式
技术细节
让我们分解一下该模式的内部工作原理:
// The [TypeException] property creates an unconstructable type because: // 1. The symbol cannot be constructed at runtime // 2. The property is a template literal type containing useful information // 3. TypeScript will try to unify this type with any attempted implementation // When you try to implement a type with TypeException: type Invalid = { [TypeException]: string; }; // TypeScript cannot create a value matching this type because: // - The TypeException symbol is not constructable // - The property type is a literal template that cannot be satisfied const invalid: Invalid = { // No possible implementation can satisfy this type };
相对于传统方法的优势
- 清除错误消息:您会收到自定义消息来准确解释出现的问题,而不是 typescript 的默认类型错误
- 编译时安全:所有错误都会在开发过程中捕获,而不是在运行时
- 自我记录:错误消息可以包含有关如何解决问题的说明
- 类型安全:保持完整的类型安全,同时提供更好的开发者体验
- 零运行时成本:所有检查都在编译时进行,没有运行时开销
结论
使用带有自定义错误消息的不可构造类型是创建自文档类型约束的强大模式。它利用 typescript 的类型系统在编译时提供清晰的指导,帮助开发人员在问题成为运行时问题之前捕获并修复问题。
在构建某些组合无效的复杂类型系统时,此模式特别有价值。通过使无效状态不可表示并提供清晰的错误消息,我们可以创建更易于维护且对开发人员友好的 typescript 代码。
本篇关于《使用不可构造类型的 TypeScript 中的丰富编译时异常》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!
声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
最新阅读
更多>
-
444 收藏
-
315 收藏
-
428 收藏
-
308 收藏
-
422 收藏
-
204 收藏
-
496 收藏
-
341 收藏
-
429 收藏
-
362 收藏
-
452 收藏
-
121 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习