Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does accessing a property of indexOf still compile?

I made a typo in TypeScript which was picked up during code review.

I used someArray.indexOf[someObject] instead of someArray.indexOf(someObject).

I would expect an error from the IDE/Compiler. Instead, no errors were raised and the result was simply undefined.

Can anyone explain this?

like image 914
De Wet van As Avatar asked Jan 18 '19 12:01

De Wet van As


People also ask

How does indexOf work JavaScript?

indexOf() The indexOf() method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring.

How do you use indexOf in array of objects?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

How do you find the index of an object in an array in TypeScript?

TypeScript - Array indexOf() indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


Video Answer


1 Answers

Quite easy.

someArray.indexOf you know that this is a function, which is also an object and can have properties.

By doing someArray.indexOf[someObject], you are trying to reach the property with the key valued to the value of someObject.

Of course, it is not defined on the indexOf function, so it returns undefined.

Quick example that illustrates the syntax and the fact that a function can have properties ;) :

const array = [];  array.indexOf['anyValue'] = 'test';  console.log(array.indexOf.anyValue);

EDIT

Here is an attempt of an answer for the TypeScript side of the question.

As you already know, TypeScript is designed to be compatible with JavaScript. Therefore, as in JS, you can access a property of an object by the following ways:

  • 'Statically': obj.property
  • 'Dynamically': obj['property']

By using the 'static' way to access a property, of course, TypeScript will raise an error!

But with the dynamic way of accessing the property, there is no way TypeScript compiler can determine the type of it or if it exists or not, since the value between bracket will be evaluated at runtime, after TypeScript transpiling.

That's why it will be implicitly marked as any.

As David Sherret mentioned in his answer, you can force TypeScript to raise an error by adding the flag --noImplicitAny, please refer to his answer for more details about this!

Hoping this helps ;)

like image 107
sjahan Avatar answered Oct 18 '22 04:10

sjahan