Learn more about an underused Typescript feature
进一步了解未被充分利用的 Typescript 功能
Recently, I’ve come across a Typescript feature that I almost never used, even after 4 years of developing applications with the language: assert functions. And now that I know about them, it feels like something every Typescript application should be using! Here is why you should check it out yourself!
最近,我遇到了一个我几乎从未使用过的 Typescript 功能,即使在使用该语言开发应用程序 4 年之后也是如此:断言函数。现在我了解了它们,感觉就像每个 Typescript 应用程序都应该使用它们!这就是为什么你应该亲自检查一下!
In this article, we will explore how to implement assertions in your TypeScript code, and the benefits of doing so.
在本文中,我们将探讨如何在 TypeScript 代码中实现断言,以及这样做的好处。
-What are TypeScript Assert Functions?
-什么是TypeScript断言函数?
You can use assert functions to validate conditions and ensure assumptions in TypeScript. If an assertion fails, the code throws a runtime error that helps you find potential programming mistakes.
你可以使用断言函数来验证条件并确保 TypeScript 中的假设。如果断言失败,代码会抛出一个运行时错误,帮助你找到潜在的编程错误。
When using this feature in TypeScript projects, you can:
在 TypeScript 项目中使用此功能时,您可以:
- Validate assumptions
- 验证假设
- Ensure code correctness
- 确保代码正确性
- Catch errors early in the development process
- 在开发过程尽早发现错误
Syntax and Usage
语法和用法
The syntax involves using assertion signatures. 语法涉及使用断言签名。
Let’s look at the example below:让我们看下面的例子:
`function assertIsString(val: any): asserts val is string {
if (typeof val !== "string") {
throw new AssertionError("Not a string!");
}
}`
Here, assertIsString tests if the passed variable is a string and throws an error if it's not. Different types of assert functions can be created, depending on the specific use case.
在这里,assertIsString函数测试传入的变量是否为字符串,如果不是,则抛出错误。可以根据具体的使用情况创建不同类型的assert函数。
Best Practices
最佳实践
To get the most out of assert functions:
为了充分利用断言函数:
- Use them strategically to validate crucial assumptions that could lead to errors if not met.
1.请策略性地使用它们来验证关键的假设,如果不满足这些假设可能会导致错误。
- Create custom assert functions specific to your application’s requirements.
2.根据您的应用程序要求创建特定的自定义断言函数。
- Focus on potential pain points and error-prone areas in your code.
3.关注代码中潜在的痛点和容易出错的区域
- Avoid using them excessively, as they can make the code harder to read and maintain.
4.避免过度使用它们,因为它们会使代码更难阅读、维护。
Use Cases
使用案例
Assert functions can be commonly found in real-world applications:
断言函数在实际应用中很常见:
- To validate function inputs
- 用于验证函数的输入
- To ensure that objects follow a specific structure
- 确保对象遵循特定的结构
- To check results from external services
- 检查来自外部服务的结果 Let’s look at a code snippet showcasing a practical example :
让我们看一下展示实际示例的代码片段:
function getUserAge(user: { name: string, age: number | null }): number {
if (user.age === null) {
throw new Error("User age is not defined");
}
return user.age;
}
As you can see, this function is checking that a user object has an age property. If not, it throws an error and breaks execution of the application. You can also use a throw statement inside a try/catch block:
正如您所看到的,该函数正在检查用户对象是否具有年龄属性。如果不是,它会抛出错误并中断应用程序的执行。您还可以在 try/catch 块内使用 throw 语句:
try {
throw new Error("Something went wrong!");
} catch (e) {
console.log(e);
}
By using assert functions in this manner, you can improve code reliability, maintainability, and ease the debugging process.
通过以这种方式使用断言函数,您可以提高代码的可靠性、可维护性并简化调试过程。
In summary
总之
You must use assert functions when creating reliable and error-free applications in TypeScript. By following best practices and combining assert functions with TypeScript, you can significantly improve the quality of your code. I encourage you to check TypeScript documentation and start experimenting with assert functions in your projects.
在 TypeScript 中创建可靠且无错误的应用程序时,您必须使用断言函数。通过遵循最佳实践并将断言函数与 TypeScript 相结合使用,您可以显着提高代码质量。我鼓励您检查TypeScript 文档并开始在项目中尝试使用断言函数。
【关于TalkX】
TalkX是一款基于GPT实现的 IDE智能开发插件,专注于编程领域,是开发者在日常编码中提高编码效率及质量的辅助工具,TalkX常用的功能包括但不限于:解释代码、中英翻译、性能检查、安全检查、样式检查、优化并改进、提高可读性、清理代码、生成测试用例等。
TalkX建立了全球加速网络,不需要考虑网络环境,响应速度快,界面效果和交互体验更流畅。并为用户提供了OpenAI的密钥,不需要ApiKey,不需要自备账号,不需要魔法。
TalkX产品支持:JetBrains (包括 IntelliJ IDEA、PyCharm、WebStorm、Android Studio)、HBuilder、VS Code、ProductId.
PS:大家最关心的问题来咯!TalkX功能免费使用, GPT4的完美平替!
【参考文献】
*上述译文仅供参考,原文请查看下面链接,解释权归原作者所有
文章:《I bet you never used TypeScript assert functions bef》
作者:Abdelfattah Sekak
发表日期:2023年8月11日
⚠️:文章内容如有翻译上的错误或者纰漏,欢迎各位评论区指正,感谢阅读!