声明方式 *[]
/* 数组的类型 */
// 声明数组都为string
let myFriends_2301: string[] = ['aaa', 'bbb']
myFriends_2301.push(1) //报错
// 声明数组都为联合类型
let myFriends_2302: (string | number)[] = ['aaa', 123]
// 声明数组都为Object
let myFriends_2303: {
name: string,
}[] = [{ name: 'aaa' }, { name: 'bbb' }]
myFriends_2303.push(1) //报错
类型推论 - 数组
/* 类型推论 - 数组 */
// 推论为string
let myFriends_2304 = ['aaa', 'bbb']
myFriends_2304.push(1) //报错
// 推论为string | number
let myFriends_2305 = ['aaa', 'bbb', 7]
myFriends_2305.push(1) //正确
myFriends_2305[2].toFixed(2) //报错,推论为联合类型,非共有属性
答案
解析
变量 animal 被赋值为数组,因此变量 animal 会被推论为具体的数组类型。
- A - 本选项的联合类型中均为基本数据类型。故错误。
- B - any 不是具体的数组类型。故错误。
- C - 本选项是对象类型。故错误。
- D - 该选项是数组类型,且数组元素的结构类型和赋值对象的结构类型相符。故正确。