如何将类构造函数的数组输入参数指定为const只读类型
解决TypeScript只读数组传入构造函数的类型错误
问题原因
你用as const声明的lastYearGrades是只读元组类型,但构造函数的参数grades被定义为Array<number>(可变数组类型)。TypeScript会阻止这种赋值——因为可变数组允许修改元素,这会破坏你要求的“数组内容不可修改”的约束,同时违反了readonly类型的设计初衷。
解决方案
把构造函数的grades参数类型改为只读数组类型,同时保留private readonly修饰符,这样既兼容as const生成的只读数组,又能满足你的两个需求:
修改后的代码
class Student { // 将参数类型改为 readonly number[](或 ReadonlyArray<number>) constructor(private readonly grades: readonly number[]) {} getMaxGrade() { return Math.max(...this.grades); } } const lastYearGrades = [94, 86, 90] as const; const s = new Student(lastYearGrades);
需求验证
- 数据成员
grades不可被修改:private readonly修饰符会阻止你在类内部重新赋值this.grades(比如this.grades = []会直接报错)。 grades的内容不可被修改:readonly number[]类型会禁止你修改数组元素(比如this.grades[0] = 100会触发类型错误)。
内容的提问来源于stack exchange,提问作者OrenIshShalom
相关产品推荐
相关产品推荐

