TypeScript 数组
TypeScript 具有用于输入数组的特定语法。
可以访问本站的 JavaScript 数组章节 学习更多的 JS 数组知识。
const names: string[] = [];names.push("Dylan"); // no errornames.push(3); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.console.log(names);
只读
readonly 关键字可以防止数组被更改。
const names: readonly string[] = ["Dylan"];names.push("Jack"); // Error: Property 'push' does not exist on type 'readonly string[]'.// try removing the readonly modifier and see if it works?console.log(names);
类型推断
如果数组有值,TypeScript 可以推断数组的类型。
const numbers = [1, 2, 3]; // inferred to type number[]numbers.push(4); // no error// comment line below out to see the successful assignmentnumbers.push("2"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.console.log(numbers);let head: number = numbers[0]; // no errorconsole.log(head);