TypeScript 数组

TypeScript 有用于输入数组的特定语法。

参阅:JavaScript 数组

实例

const names: string[] = [];
names.push("Dylan"); // 无错误
// names.push(3); // 错误:类型为 'number' 的参数不能分配给类型为 'string' 的参数。

亲自试一试

Readonly

readonly 关键字可以防止数组被更改。

实例

const names: readonly string[] = ["Dylan"];
names.push("Jack"); // 错误:类型 'readonly string[]' 上不存在属性 'push'。
// 尝试删除 readonly 修饰符,看看是否有效?

亲自试一试

类型推断

如果数组有值,TypeScript 可以推断数组的类型。

实例

const numbers = [1, 2, 3]; // inferred to type number[]
numbers.push(4); // 无错误
// 注释掉下面的行以查看成功的分配
numbers.push("2"); // 错误:类型为 'string' 的参数不能分配给类型为 'number' 的参数。  
let head: number = numbers[0]; // 无错误

亲自试一试