TypeScript--数组
「类型 + 方括号」表示法
示例
// ✅正确
const nums1: number[] = [1, 2, 3, 4]
// ❌错误
// Type 'number' is not assignable to type 'string'.
// 数组的项中不允许出现其它的类型
const nums2: string[] = ['a', 'b', 'c', 1]
// ✅正确
nums1.push(1)
// ❌错误
// Argument of type 'string' is not assignable to parameter of type 'number'.
nums1.push('1')
数组泛型 「Array<elemType>」
示例
// ✅正确
const nums1: Array<string> = ['a', 'b', 'c']
// ✅正确
nums2.push('a')
// ❌错误
// Argument of type 'string' is not assignable to parameter of type 'number'.
nums2.push(1)
any
在数组中的应用
用 any
表示数组中允许出现任意类型
示例
const list: any[] = ['a', 1, true, null, undefined, {}]