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]; // 推断为类型 number[]
numbers.push(4); // 没有错误
// 注释掉下面的行,查看是否成功赋值
numbers.push("2"); // 错误:类型为“string”的参数不能赋值给类型为“number”的参数。
let head: number = numbers[0]; // 没有错误
总结
本文介绍了TypeScript 数组的使用,如有问题欢迎私信和评论