tl;dr: typescript 实用程序类型是预先构建的函数,可以转换现有类型,使您的代码更干净且更易于维护。本文通过实际示例解释了基本实用程序类型,包括如何更新用户配置文件、管理配置和安全地过滤数据。

typescript 是现代 web 开发的基石,使开发人员能够编写更安全、更易于维护的代码。通过向 javascript 引入静态类型,typescript 有助于在编译时捕获错误。根据 2024 年 stack overflow 开发者调查,typescript 在开发者中最流行的脚本技术中排名第 5。
typescript 令人惊叹的功能是其成功的主要原因。例如,实用程序类型可以帮助开发人员简化类型操作并减少样板代码。 typescript 2.1 中引入了实用程序类型,并且每个新版本中都添加了其他实用程序类型。
本文将详细讨论实用程序类型,以帮助您掌握 typescript。
了解 typescript 实用程序类型
实用程序类型是 typescript 中预定义的泛型类型,可以将现有类型转换为新的变体类型。它们可以被认为是类型级函数,将现有类型作为参数并根据某些转换规则返回新类型。
这在使用接口时特别有用,因为通常需要修改已存在类型的变体,而实际上不需要复制类型定义。
核心实用程序类型及其实际应用

部分的
partial 实用程序类型采用一个类型并使其所有属性都是可选的。当类型嵌套时,此实用程序类型特别有价值,因为它使属性递归地可选。
例如,假设您正在创建一个用户配置文件更新功能。在这种情况下,如果用户不想更新所有字段,则可以只使用 partial 类型,只更新所需的字段。这在不需要所有字段的表单和 api 中非常方便。
请参考以下代码示例。
interface user { id: number; name: string; email?: string;}const updateuser = (user: partial) => { console.log(updating user: ${user.name} );};updateuser({ name: 'alice' });
必需的
required 实用程序类型构造一个类型,并将所提供类型的所有属性设置为 required。这对于确保在将对象保存到数据库之前所有属性都可用非常有用。
例如,如果在汽车注册时使用必填,它将确保您在创建或保存新汽车记录时不会错过任何必要的属性,例如品牌、型号和里程。这对于数据完整性而言非常关键。
请参考以下代码示例。
interface car { make: string; model: string; mileage?: number;}const mycar: required = { make: 'ford', model: 'focus', mileage: 12000,};
只读
readonly 实用程序类型创建一个所有属性都是只读的类型。这在配置管理中非常有用,可以保护关键设置免受不必要的更改。
例如,当您的应用程序依赖于特定的 api 端点时,它们不应在执行过程中发生更改。将它们设置为只读可以保证它们在应用程序的整个生命周期中保持不变。
请参考以下代码示例。
interface config { apiendpoint: string;}const config: readonly = { apiendpoint: 'https://api.example.com' };// config.apiendpoint = 'https://another-url.com'; // error: cannot assign to 'apiendpoint'
挑选
pick** 实用程序类型通过从现有类型中选取一组属性来构造类型。当您需要过滤掉重要信息(例如用户姓名和电子邮件)以显示在仪表板或摘要视图中时,这非常有用。它有助于提高数据的安全性和清晰度。
请参考以下代码示例。
interface user { id: number; name: string; email: string;}type usersummary = pick;const usersummary: usersummary = { name: 'alice', email: 'alice@example.com',};
忽略
omit 实用程序类型通过从现有类型中排除特定属性来构造类型。
例如,如果您想与某些第三方共享用户数据但没有敏感信息(例如电子邮件地址),省略将很有用。您可以通过定义一个排除这些字段的新类型来做到这一点。特别是在 api 中,您可能想观察 api 响应中的外部内容。
请参阅下一个代码示例。
interface user { id: number; name: string; email?: string;}const userwithoutemail: omit = { id: 1, name: 'bob',};
记录
record 实用程序类型创建具有指定键和值的对象类型,这在处理结构化映射时非常有用。
例如,在库存管理系统的上下文中,record 类型可用于在项目和数量之间进行显式映射。通过这种类型的结构,可以轻松访问和修改库存数据,同时确保所有预期的水果都得到考虑。
type fruit = 'apple' | 'banana' | 'orange';type inventory = record;const inventory: inventory = { apple: 10, banana: 5, orange: 0,};
排除
排除**实用程序类型通过从联合中排除特定类型来构造类型。
在设计只接受某些基元类型(例如数字或布尔值,但不接受字符串)的函数时,可以使用 排除。这可以防止意外类型可能在执行过程中导致错误的错误。
请参考以下代码示例。
type primitive = string | number | boolean;const value: exclude = true; // only allows number or boolean.
提炼
extract 实用程序类型通过从联合中提取特定类型来构造类型。
在只需要处理混合类型集合中的数值(例如执行计算)的情况下,使用 extract 可确保仅传递数字。这在数据处理管道中非常有用,其中严格的类型可以防止运行时错误。
请参考以下代码示例。
type primitive = string | number | boolean;const value2: extract = 42; // only allows numbers.
不可为空
nonnullable 实用程序类型通过从给定类型中排除 null 和 undefined 来构造类型。
在需要始终定义某些值(例如用户名或产品 id)的应用中,将它们设置为 nonnullable 将确保此类关键字段永远不会为 null 或 未定义。它在表单验证和 api 响应期间非常有用,因为缺少值可能会导致问题。
请参阅下一个代码示例。
type nullablestring = string | null | undefined;const value3: nonnullable = 'hello'; // null and undefined are not allowed.
返回类型
returntype 实用程序提取函数的返回类型。
当使用返回复杂对象(例如坐标)的高阶函数或回调时,使用 returntype 可以简化定义预期的返回类型,而无需每次都手动声明它们。这可以通过减少与类型不匹配相关的错误来加快开发速度。
type pointgenerator = () => { x: number; y: number };const point: returntype = { x: 10, y: 20,};
参数
参数实用程序将函数的参数类型提取为元组。
在想要动态操作或验证函数参数的情况下,例如在函数周围编写包装器时,这可以轻松提取和重用参数类型。通过确保函数签名的一致性,它极大地提高了代码库中代码的可重用性和可维护性。
请参考以下代码示例。
function createuser(name: string, age: number): user { return { name, age };}type createuserparams = parameters;
具有实用程序类型组合的高级用例
使用 typescript 开发应用程序时,组合这些实用程序类型可以获得强大的结果。让我们看一下多种实用程序类型有效协同工作的一些场景。
结合部分和必需
您可以创建一个需要某些字段而允许其他字段可选的类型。
interface user { id: number; name?: string; email?: string;}// combining partial and requiredtype updateuser = required<pick> & partial<omit>;const updateuserdata: updateuser = { id: 1, name: 'alice' }; // valid
在此示例中,updateuser 需要 id 属性,同时允许名称和电子邮件为可选。此模式对于更新标识符必须始终存在的记录非常有用。
创建灵活的 api 响应
您可能想要定义根据特定条件具有不同形状的 api 响应。
interface apiresponse { data?: t; error?: string;}// using record with omit for flexible responsestype userresponse = apiresponse<pick>;const response1: userresponse = { data: { name: 'alice', email: 'alice@example.com' } };const response2: userresponse = { error: 'user not found' };
这里,apiresponse 允许您为 api 调用创建灵活的响应类型。通过使用 pick ,您可以确保响应中仅包含相关的用户数据。
结合排除和提取来过滤类型
您可能会遇到需要根据特定条件从联合中过滤掉特定类型的情况。
请参考以下代码示例。
type responsetypes = 'success' | 'error' | 'loading';// extracting specific response types while excluding otherstype nonloadingresponses = exclude;const handleresponse = (responsetype: nonloadingresponses) => { if (responsetype === 'success') { console.log('operation was successful!'); } else if (responsetype === 'error') { console.log('an error occurred.'); }};handleresponse('success'); // valid call// handleresponse('loading'); // error as loading is excluded
这里,exclude 实用程序用于创建一个类型 ( nonloadingresponses ),从原始 responsetypes 联合中排除 loading,允许 handleresponse 函数仅接受成功或错误作为有效输入。
最佳实践
仅使用必要的
虽然实用程序类型非常强大,但过度使用它们可能会导致复杂且不可读的代码。在利用这些实用程序和保持代码清晰度之间取得平衡至关重要。
请参阅下一个代码示例。
type user = { id: number; name: string; email?: string;};// overly complex type using multiple utilities.type complexuser = partial<required<pick>>;// this can be confusing and hard to maintain.const user1: complexuser = { name: 'alice' }; // valid, but unclear intent
保持清晰度
确保每个实用程序用例的目的明确。避免将太多实用程序嵌套在一起,因为它可能会混淆类型的预期结构。
请参考以下代码示例。
type product = { id: number; name: string; description?: string; price: number;};// clear and understandable use of utility types.type productpreview = pick;const preview: productpreview = { id: 101, name: 'smartphone',};
性能考虑
虽然在运行时性能影响很少,因为 typescript 类型在编译后消失,但复杂类型会减慢 typescript 编译器的速度,影响开发速度。
// A complex type that could impact performance if used excessively.type DeeplyNestedType = { level1: { level2: { level3: { level4: { level5: string; }; }; }; };};// Accessing deeply nested properties can lead to performance issuesconst example: DeeplyNestedType = { level1: { level2: { level3: { level4: { level5: 'Hello', }, }, }, },};console.log(example.level1.level2.level3.level4.level5); // Performance hit on deep access
结论
毫无疑问,typescript 是 web 开发人员中最流行的语言之一。实用程序类型是 typescript 中的独特功能之一,如果正确使用,它可以显着提高 typescript 开发体验和代码质量。但是,我们不应该在所有场景中都使用它们,因为可能会出现性能和代码可维护性问题。
相关博客
javascript 和 typescript 的顶级 linters:简化代码质量管理每个开发人员都应该知道的 7 个 javascript 单元测试框架typescript 中感叹号的使用理解 typescript 中的条件类型
以上就是TypeScript Utility Types: A Complete Guide的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1499035.html
微信扫一扫
支付宝扫一扫