打字稿:错误TS2314:泛型类型'Array <t>'需要1个类型的参数

时间:2018-04-11 07:19:51

标签: typescript

我正在学习打字稿,而且我已经编写了非常基本的代码。

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:泛型类型'Array'需要1个类型参数 我在哪里做错了?

2 个答案:

答案 0 :(得分:1)

通用数组必须定义为:

  • const arr = new Array<string>()
  • const arr = string[]

答案 1 :(得分:1)

建议使用T [] sythax而不是Array&lt; T> synthax

TSlint rule&#34; array-type&#34;:[true,&#34; array&#34;]:

对于你的代码,Array [string]应该是Array&lt;字符串&gt;为了编译。

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,它将帮助您编写干净的Typescript代码。