wangdoc / typescript-tutorial

TypeScript 教程
https://wangdoc.com/typescript
2.43k stars 256 forks source link

不理解 ts中 number[]是readonly number[]类型? #117

Closed notflybird closed 3 weeks ago

notflybird commented 3 weeks ago
  在学习array.md数组类型的时候,对于“TypeScript 将readonly number[]与number[]视为两种不一样的类型,后者是前者的子类型”这句话不太理解,虽然number[]生成的数据能够赋值给 readonly number[]声明的变量,反过来不行。
 但是我觉得number[]普通数组类型是宽泛的、是父类,readonly number[] 是继承了 number[] 类型多了只读属性进行约束,是子类型。
  不知道如何解释?请大佬帮忙解释一下,谢谢!
notflybird commented 3 weeks ago

我明白了,从父集和子集包含关系来说:父类型定义的内容,子类型肯定能是有的,因为子类型继承父类型,然后子类型可以在定义一些自己内容;readonly number[]作为父类型,有“读取”方法、获取数组长度等,number[]子类型继承父类型,在原来的基础上,新增push、pop、unshift、shift等方法;这样就导致子类型number[]在父类型基础上进行了扩展;所以number[]值可以赋值给readonly number[],但是反过来不行,因为readonly number[]类型值,没有push,pop等方法。不知道理解的对吗?