Typescript error message TS2314: One type argument is required for the generic type 'Array<T>'

I recently started my journey in learning typescript and have written some basic code.

class Learning {

    subjects: Array[string];
    hoursPerDay: number;

    constructor(subj: Array[string], hrs: number) {
        this.subjects = subj;
        this.hoursPerDay = hrs;
    }

    displaySubjects():void{

        for(let i=0; i<this.subjects.length; i++){
            console.log(this.subjects[i]);
        }
    }
}
let topics=["Math", "Science", "History"];
let learning = new Learning(topics, 5);

learning.displaySubjects();

I am encountering an error whenever I use an array:

Error TS2314: Generic type 'Array' requires 1 type argument(s). What am I doing wrong?

Answer №1

It is important to define generic arrays correctly:

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

Answer №2

It is suggested to use the T[] syntax instead of Array< T > syntax.

The TSlint rule "array-type": [true, "array"]:

To ensure compilation, change Array[string] to Array < string > in your code.

nameOfStudents: Array<string>;
noOfteachers: number

constructor(name: Array<string>, no: number) {
    this.nameOfStudents = name;
    this.noOfteachers = no;
}

A better practice would be like this:

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);
        }
    }
}

I highly recommend installing tslint for your project as it helps maintain clean Typescript code.

EDIT 18/12/22: tslint is deprecated, use eslint instead

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues arise when Typescript fails to convert an image URL into a base64 encoded string

My current challenge involves converting an image to base 64 format using its URL. This is the method I am currently using: convertToBase64(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.he ...

Setting up a ts-node project with ECMAScript modules. Issue: Unrecognized file extension ".ts"

I am currently in the process of setting up a minimalistic repository that incorporates ts-node and ESM for a project. Despite the existence of previous inquiries on this topic, I have encountered numerous outdated responses. Even recent answers appear to ...

Break free/Reenter a function within another function

Is there a way to handle validation errors in multiple task functions using TypeScript or JavaScript, and escape the main function if an error occurs? I am working in a node environment. const validate = () => { // Perform validation checks... // ...

Struggled with setting up the WebSocket structure in typescript

Issue Running the code below results in an error: index.tsx import WebSocket from 'ws'; export default function Home() { const socket = new WebSocket('ws://localhost:1919/ws'); return ( <div>Home</div> ); } ...

A single element containing two duplicates of identical services

I am encountering an issue with my query builder service in a component where I need to use it twice. Despite trying to inject the service twice, it seems that they just reference each other instead of functioning independently, as shown below: @Component( ...

Deciphering TS2345: "The argument supplied, known as 'typeof MyComponent', cannot be assigned to the specified parameter type"

I am facing an issue while attempting to integrate a Typescript React component with react-onclickoutside. The error message that I encounter is as follows: TS2345: Argument of type 'typeof MyComponent' is not assignable to parameter of type &apo ...

Tips for obtaining the most recent HTML element in Angular

I was able to include HTML content in an Angular (7) UI using the DomSanitizer this.sanitizer.bypassSecurityTrustHtml("htmlstr") Once the content is sanitized and displayed in the HTML view, users have the ability to modify the values as desired ...

Form validation is an essential feature of the Angular2 template-driven sub form component

I'm currently working on a template-driven form that includes a group of inputs generated through an ngFor. My goal is to separate this repeating 'sub-group' into its own child component. However, I'm encountering difficulties in ensur ...

Encountering an issue while developing a Discord bot using TypeScript

Hello, I'm currently working on creating a nick command for my discord bot in TypeScript, but I encountered an error. Here is the issue: Error: Expression expected.ts (1109) When I replace const mentionedMember = message? message.mentions.members? ...

Lack of code completion in Nuxt options API when using typescript

After setting up Nuxtjs with typescript, I noticed that there are no code completions in the template and script as expected based on the title. Here is the code: <script lang="ts"> import Vue from 'vue'; import { FeaturedJobs } ...

Can someone explain how to define "a type of object that must not be empty" in typescript?

I'm working with a function that can operate on any type T, but with the constraint that if T is an object, it cannot potentially be empty. Here's what I've tried: declare function myFunction<T>(param: T extends Record<string, neve ...

How can I enable dragging functionality for components (not elements) in angular?

While utilizing the Angular CDK drag and drop module, I have observed that it functions seamlessly on html elements like div, p, etc. However, when I apply a cdkDrag directive to a component, it does not seem to work as expected. <!-- IT WORKS --> ...

What steps do I need to follow to develop a checkbox component that mirrors the value of a TextField?

I am working with 3 components - 2 textfields and 1 checkbox Material UI component. My goal is to have the checkbox checked only when there is a value in one of the textfield components. What would be the most effective way to achieve this functionality? ...

How can I run a TypeScript function within a JavaScript file?

I am working with a typescript file named file1.ts export function Hello(str: string) { console.log(str); } In addition, I have another file called index.js { require('./some.js'); } Furthermore, there is a script defined in the pack ...

Error occurred when trying to import an external module using an invalid hook call

I am creating a package named "Formcomponent" using React and React Bootstrap. This code is from index.tsx /** * Renders a component for a form. */ import React from "react"; import Form from "react-bootstrap/Form"; /** * List of props * @returns */ ...

Fix React/Typescript issue: Exported variable conflicts with name from external module

I am encountering a perplexing issue when using React with Redux and Typescript. The error message I am receiving is unfamiliar to me, and I am unsure how to resolve it. The error states: Exported variable 'rootReducer' has or is using name ...

Converting retrieved data into table cells through mapping

I'm facing an issue where I need to display specific addresses for each individual in a table row. For simplicity, let's focus on showing the city specifically as described in this code snippet: https://i.stack.imgur.com/bJmsD.png Currently, whe ...

Angular2 Cache: Enhance Your Application's Performance

Currently seeking a cache solution for my Angular2 application. Imagine we have a massive collection of Movie objects stored on a server, too many to fetch all at once. The server offers a REST endpoint: getMovie(String id) On the client side, I need a s ...

Dealing with a void method in a React unit test by treating it as an object's property

How can I pass a value to a function in an interface to trigger a click event on an element? I have a React component that I want to write unit tests for: const VariantItem = (props: VariantItem): ReactElement => { return ( <div key={props.produc ...

Filtering without the includes() Method

I have two Objects that are structured as follows: export const recipes: Recipe[] = [ new Recipe( id: "Green", scenario: ["1", "2"]), new Recipe( id: "Blue", scenario: ["1", "2","2"]) ]; export const scenarios: Scenario[] = [ new Scenario( id: "1 ...