Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

TypeScript 数组


TypeScript 有一种特定的语法来为数组指定类型。

在我们的 JavaScript 数组章节 中了解更多关于数组的信息。

示例

const names: string[] = [];
names.push("Dylan"); // 无错误
// names.push(3); // 错误:类型“number”的参数不能分配给类型“string”的参数。
自己尝试 »

只读

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

示例

const names: readonly string[] = ["Dylan"];
names.push("Jack"); // 错误:属性“push”不存在于类型“readonly string[]”上。
// 尝试移除 readonly 修饰符并查看是否有效?
自己尝试 »

类型推断

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

示例

const numbers = [1, 2, 3]; // 推断为类型 number[]
numbers.push(4); // 无错误
// 注释掉下面一行代码以查看成功的赋值
numbers.push("2"); // 错误:类型“string”的参数不能分配给类型“number”的参数。
let head: number = numbers[0]; // 无错误
自己尝试 »

TypeScript 练习

通过练习测试自己

练习

防止数组被修改

const names:  string[] = ["Dylan"];
        

开始练习


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.