承接上一课typescript原始类型学习,本课将深入讲解typescript中的对象和数组。
本课程将涵盖TypeScript对象和数组的创建和使用技巧。我们将学习多种创建对象和数组的方法,并了解它们各自的适用场景。
创建对象的简便方法是使用对象字面量。此方法适用于预先已知对象属性的情况,因为之后无法直接添加新属性。
<code class="typescript">const myObject = {
keyA: 'valueA',
keyB: 'valueB',
};
myObject.keyC = 'valueC'; // 这行代码在运行时可能会报错,取决于编译器的strictNullChecks设置。</code>
当对象属性未知时,索引签名提供了一种创建动态对象的方法。
<code class="typescript">const myObject: { [key: string]: string } = {
keyA: 'valueA',
keyB: 'valueB',
};
myObject.keyC = 'valueC';
console.log(myObject);</code>
Record是TypeScript中的一种实用程序类型,用于创建键值对类型都已知的动态对象。
<code class="typescript">const myObject: Record<string, string> = {
keyA: 'valueA',
keyB: 'valueB',
};</code>
创建数组最直接的方式是使用数组字面量,即用方括号括起来的逗号分隔的元素列表。
<code class="typescript">const numberArray: number[] = [1, 2, 3]; const stringArray: string[] = ['josh', 'patrick', 'lamar']; const mixedArray: (string | number)[] = [1, 'alice', 55]; console.log(stringArray); console.log(numberArray); console.log(mixedArray);</code>

另一种创建数组的方法是使用数组构造函数。
<code class="typescript">const numberArray: Array<number> = [1, 2, 3]; const stringArray: Array<string> = ['Josh', 'Patrick', 'Lamar']; const mixedArray: Array<string | number> = [1, 'Alice', 55]; console.log(stringArray); console.log(numberArray); console.log(mixedArray);</code>

课程代码可在以下链接获取: https://www.php.cn/link/dfddbc8b408814a212486f2a94b8cabf
下一课我们将学习TypeScript中的函数,包括参数类型、返回类型等。
欢迎评论并分享本文,共同学习TypeScript!
以上就是免费打字稿课堂课程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号