An element access expression should take an argument in TS

avatar

Borislav Hadzhiev

Wed Mar 23 20222 min read

An element access expression should take an argument in TS #

The error "An element access expression should take an argument" occurs when we try to assign a type where a value is expected. To solve the error, make sure to separate a type assignment by colon and a value assignment by an equal sign.

element access expression should take argument

Here is an example of how the error occurs.

index.ts
class Employee { // ⛔️ Parsing error: An element access expression should take an argument tasks = string[]; }

The issue is that when assigning a type for the class property, we need to use a colon between the property name and the type, and not an equal sign.

index.ts
class Employee { tasks: string[] = []; }

Now the tasks property has a type of string[] and is initialized to an empty array.

The error "An element access expression should take an argument" also occurs when we try to write TypeScript in a file with a .js or other extension, especially in a React.js application. Make sure your file has a .ts or .tsx extension.

You can also use the constructor to initialize the property if you expect to take it as a parameter when the class is instantiated.

index.ts
class Employee { constructor(public tasks: string[] = []) { this.tasks = tasks; } } const emp = new Employee(['develop', 'test']); console.log(emp.tasks); // 👉️ ['develop', 'test'] emp.tasks.push('ship'); console.log(emp.tasks); // 👉️ ['develop', 'test', 'ship']

Here is another example of how the error occurs.

index.ts
class Developer { language = 'TypeScript'; } class Employee { // ⛔️ Parsing error: An element access expression should take an argument developers = Developer[]; }

The error was caused, because we assigned the Developer type as a value.

To solve the error, we have to separate the type and the property name with a colon.

index.ts
class Developer { language = 'TypeScript'; } class Employee { developers: Developer[] = []; } const emp = new Employee(); emp.developers.push(new Developer()); console.log(emp.developers); // 👉️ [Developer {language: 'TypeScript'}]

We typed the developers property as an array of Developer type and initialized it to an empty array to solve the error.

Use the search field on my Home Page to filter through my more than 1,000 articles.