1

I'm having a typescript error with my Ionic/Angular application. Below it says:

Type 'string[]' cannot be used as an index type.

Which I don't understand. The entire error is:

[17:57:57] typescript: C:/xampp/htdocs/project x/anonymous-social/src/pages/threads/threads.ts, line: 58 Type 'string[]' cannot be used as an index type.

L58: let threadId = Object(snapshot.val()[Object.keys(snapshot.val())]).threadId;

L59: let messageCount = snapshot.val().unread || 0;

My code that goes along with this is:

this.database.database.ref('/users/'+this.userData.uid+'/threads/')
.orderByChild('threadId')
.on('child_added', (snapshot) => {
      let threadId = Object(snapshot.val()[Object.keys(snapshot.val())]).threadId;
      let messageCount = snapshot.val().unread || 0;
      rec.push(Object(snapshot.val()[Object.keys(snapshot.val())]));

Any idea why this might be happening? I don't completely understand... Any help would be great!

1 Answer 1

2

In snapshot.val()[Object.keys(snapshot.val())] you are attempting to index into snapshot.val() using Object.keys(snapshot.val()).

Object.keys returns type string[].

Is there a reason you can't just use:

let threadId = snapshot.val().threadId;

I don't see the need for all that extra logic.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, snapshot.val() returns the first line in this image: i.gyazo.com/6eddab7527e3737cb1f72b96c040d6fe.png and the Object keys stuff returns the second line...
What is the expected shape of the snapshot value? It kinda sounds like you expect it only ever to have a single key-value pair and you expect Object.keys to give you the one key. But Object.keys returns an array of keys. If you are really sure it will have one, then you can change that to Object.keys(snapshot.val())[0] and TS will be okay with it, but I stand by the opinion that there is a lot of unnecessary complexity here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.