TypeScript 数组
TypeScript 有特定的数组类型语法。
在我们的JavaScript 数组章节中了解更多关于数组的信息。
示例
const names: string[] = [];
names.push("Dylan"); // 无错误
// names.push(3); // 错误:类型 'number' 的参数不能赋值给类型 'string' 的参数。
自己动手试一试 »
只读
readonly
关键字可以防止数组被修改。
示例
const names: readonly string[] = ["Dylan"];
names.push("Jack"); // 错误:类型 'readonly string[]' 上不存在属性 'push'。
// 尝试移除 readonly 修饰符看看是否有效?
自己动手试一试 »
类型推断
如果数组有值,TypeScript 可以推断出数组的类型。
示例
const numbers = [1, 2, 3]; // 推断为 number[] 类型
numbers.push(4); // 无错误
// 注释掉下面的行以查看成功的赋值
numbers.push("2"); // 错误:类型 'string' 的参数不能赋值给类型 'number' 的参数。
let head: number = numbers[0]; // 无错误
自己动手试一试 »