You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript报错TS2314:泛型类型Array<T>需1个类型参数的问题咨询

Fixing the "Generic type 'Array' requires 1 type argument(s)" Error in TypeScript

Hey there! That error is popping up because you're using TypeScript's generic Array type incorrectly. Let's break down what's wrong and fix it step by step.

What's the Root Cause?

TypeScript's Array is a generic type, meaning it needs explicit info about what kind of elements it holds (that's the <T> referenced in the error). Your code uses Array[string] — but square brackets are the wrong syntax here. Generic types require angle brackets (<>) to define their type argument. Alternatively, you can use the shorter, more widely preferred array syntax: ElementType[].

Corrected Code

Here's your fixed code using the angle bracket syntax for Array:

class School {
  // Fixed: Use Array<string> instead of Array[string]
  nameOfStudents: Array<string>;
  noOfteachers: number;

  // Fixed: Same correction for the constructor parameter
  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();

Shorter, More Readable Alternative

Most TypeScript developers opt for the concise array syntax (ElementType[]) over Array<ElementType> for better readability. Here's the same code using this style:

class School {
  nameOfStudents: string[];
  noOfteachers: number;

  constructor(name: 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();

Quick Tip for Future Use

This rule applies to all array types in TypeScript:

  • A number array would be Array<number> or number[]
  • A boolean array would be Array<boolean> or boolean[]

That should resolve the error and get your code running as expected!

内容的提问来源于stack exchange,提问作者AConsumer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:33:41