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.
-
泛型 - 带参数的类型
¥Generics - Types which take parameters
-
keyof 类型运算符 - 使用
keyof
运算符创建新类型¥Keyof Type Operator - Using the
keyof
operator to create new types -
typeof 类型运算符 - 使用
typeof
运算符创建新类型¥Typeof Type Operator - Using the
typeof
operator to create new types -
索引访问类型 - 使用
Type['a']
语法访问类型的子集¥Indexed Access Types - Using
Type['a']
syntax to access a subset of a type -
条件类型 - 在类型系统中表现得像 if 语句的类型
¥Conditional Types - Types which act like if statements in the type system
-
映射类型 - 通过映射现有类型中的每个属性来创建类型
¥Mapped Types - Creating types by mapping each property in an existing type
-
模板字面类型 - 通过模板字面字符串更改属性的映射类型
¥Template Literal Types - Mapped types which change properties via template literal strings