Last updated: Feb 29, 2024
Reading timeยท2 min
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.
Here is an example of how the error occurs.
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.
class Employee { tasks: string[] = []; }
Now the tasks
property has a type of string[]
and is initialized to an empty
array.
.js
extensionThe 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.
You can also use the constructor to initialize the property if you expect to take it as a parameter when the class is instantiated.
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.
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.
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
types and
initialized it to an empty array
to solve the error.
You can learn more about the related topics by checking out the following tutorials: