TypeScript 的类型系统非常强大,因为它允许用其他类型来表达类型。
🌐 TypeScript’s type system is very powerful because it allows expressing types in terms of other types.
这个想法最简单的形式是泛型。此外,我们还有多种可用的 类型操作符。同样,也可以用我们已经拥有的 值 来表达类型。
🌐 The simplest form of this idea is generics. Additionally, we have a wide variety of type operators available to use. It’s also possible to express types in terms of values that we already have.
通过组合各种类型运算符,我们可以以简洁、可维护的方式表达复杂的操作和数值。在本节中,我们将介绍如何通过已有的类型或数值来表达新的类型。
🌐 By combining various type operators, we can express complex operations and values in a succinct, maintainable way. In this section we’ll cover ways to express a new type in terms of an existing type or value.
- 泛型 - 可以接收参数的类型
- Type 操作符的 Key - 使用
keyof操作符创建新类型 - Typeof 类型运算符 - 使用
typeof运算符创建新类型 - 索引访问类型 - 使用
Type['a']语法访问类型的子集 - 条件类型 - 在类型系统中类似于 if 语句的类型
- 映射类型 - 通过映射现有类型中的每个属性来创建类型
- 模板字面量类型 - 通过模板字面量字符串更改属性的映射类型