TypeScript报错TS2314:泛型类型Array<T>需1个类型参数的问题咨询
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>ornumber[] - A boolean array would be
Array<boolean>orboolean[]
That should resolve the error and get your code running as expected!
内容的提问来源于stack exchange,提问作者AConsumer

