TypeScript$Type-Value-ArrayAndTupleAndEnum
1. Array
JavaScript 中的数组可以存任意类型,对应的数组类型是 any[]。很多情况下,数组元素的类型是确定的。
对于同种类型的数组,类型的表达方式有两种:
number[]Array<number>
- Array is a generic type
interface Array<Type> {
/**
* Gets or sets the length of the array.
*/
length: number
/**
* Removes the last element from an array and returns it.
*/
pop(): Type | undefined
/**
* Appends new elements to an array, and returns the new length of the array.
*/
push(...items: Type[]): number
// ...
}
Modern JavaScript also provides other data structures which are generic, like Map<K, V>, Set<T>, and Promise<T>. All this really means is that because of how Map, Set, and Promise behave, they can work with any sets of types.
1.1 The ReadonlyArray Type
和普通 readonly 不同,ReadonlyArray 和普通的 Array 的赋值不是双向的:只可以将 Array 赋给 ReadonlyArray,相反则不行。
表达方式有两种:
ReadonlyArray<string>readonly string[]
2. Tuple
在一些编程语言中,数组的长度是固定的。在 TypeScript 中,Tuple 类型的数据就是长度固定的数组,且每个位置的类型也固定(不需要是同一种类型)。
type StringNumberPair = [string, number]
不允许通过 index 设置超过数量位置的值,但是可以通过 push 等方法改变长度。readonly Tuple 就为了解决这个问题。
function doSomething(pair: [string, number]) {
// ...
const c = pair[2];
// error, Tuple type '[string, number]' of length '2' has no element at index '2'.
pair.push(1) // OK, not recommended
pair.length // TS says 2, but in fact 3
}
- Optional properties
come at the end
type Either2dOr3d = [number, number, number?]
function setCoordinate(coord: Either2dOr3d) {
const [x, y, z] = coord
// const z: number | undefined
console.log(`Provided coordinates had ${coord.length} dimensions`);
// (property) length: 2 | 3
}
- Rest elements
length 不确定
type StringNumberBooleans = [string, number, ...boolean[]];
type StringBooleansNumber = [string, ...boolean[], number];
type BooleansStringNumber = [...boolean[], string, number];
2.1 readonly Tuple Types
function doSomething(pair: readonly [string, number]) {
// ...
}
function doSomething(pair: readonly [string, number]) {
pair[0] = "hello!";
// error, Cannot assign to '0' because it is a read-only property.
}
let point = [3, 4] as const;
function distanceFromOrigin([x, y]: [number, number]) {
return Math.sqrt(x ** 2 + y ** 2);
}
distanceFromOrigin(point);
// error, Argument of type 'readonly [3, 4]' is not assignable to parameter of type '[number, number]'.
// The type 'readonly [3, 4]' is 'readonly' and cannot be assigned to the mutable type '[number, number]'.
3. Enum
enum: a set of named constants.
enum 是 TypeScript 新增的类型,在 JavaScript 中不存在。
其他的数据类型像是“公理”——不需要什么背景,大家都知道。enum 像是“定理”,需要一点特定领域的专业知识才行。比如交通信号灯的颜色是红黄绿。这里的红黄绿的组合就是枚举类型。
在内存中,枚举类型的值是 string | number。
官网中列举了一些情况,很多更像是因为内部实现而引起的注意事项,这里就不描述了。
3.1 Define Enum
enum Direction {
Up = 1,
Down, // 2
Left,
Right,
}
enum Direction {
Up, // 0
Down,
Left,
Right,
}
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
enum BooleanLikeHeterogeneousEnum {
No = 0,
Yes = "YES",
}
3.2 Use Enum
enum UserResponse {
No = 0,
Yes = 1,
}
function respond(recipient: string, message: UserResponse): void {
// ...
}
respond("Princess Caroline", UserResponse.Yes);