An element access expression should take an argument in TS

avatar
Borislav Hadzhiev

Last updated: Feb 29, 2024
2 min

banner

# 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 a 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[]; }

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.

# Make sure you aren't writing Typescript in a file with a .js extension

The error also occurs when we try to write TypeScript in a file with a .js or another extension, especially in a React.js application.

Make sure your file has a .ts or .tsx extension.

# Using the constructor to initialize a property

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']

using constructor to initialize property

The code for this article is available on GitHub

# Another example of how the error occurs

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'}]

separate type and property name with colon

The code for this article is available on GitHub

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

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev