我正在学习打字稿,我写了非常基本的代码。
class School {
nameOfStudents: Array[string];
noOfteachers: number
constructor(name: Array[string], no: number) {
this.nameOfStudents = name;
this.noOfteachers = no;
}
printName():void{
for(let i=0;i<this.nameOfStudents.length;i++){
console.log(this.nameOfStudents[i])
}
}
}
let arr=["a","b","c","d","e"]
let school = new School(arr,100);
school.printName();
无论我在哪里使用数组,我都会收到以下错误:
错误 TS2314:泛型类型"数组"需要 1 个类型参数我哪里做错了?
泛
型数组必须定义为:
-
const arr = new Array<string>()
-
const arr = string[]
建议使用 T[] sythax 而不是 Array
规则 "array-type": [true, "array"]:
对于您的代码,Array[string] 应该是 Array <字符串>以便编译。字符串>
nameOfStudents: Array<string>;
noOfteachers: number
constructor(name: Array<string>, no: number) {
this.nameOfStudents = name;
this.noOfteachers = no;
}
最佳做法是这样的
class School {
nameOfStudents: string[];
noOfteachers: number;
constructor(name: string[], no: number) {
this.nameOfStudents = name;
this.noOfteachers = no;
}
printName(): void {
for (const studentName of this.nameOfStudents) {
console.log(studentName);
}
}
}
我强烈建议您为您的项目安装 tslint,它将帮助您编写干净的打字稿代码。
编辑 18/12/22:不推荐使用 tslint,改用 eslint