0

I know I can't use a string as a object index because it's too unspecific and for that I should use keyof but I wondering why can't I use a string even after check it is a valid index with the in operator.

Example:

if (fieldName in someObject) {
  const fieldValue = someObject[fieldName];
}

Typescript complain about this. I understand it can't compute the fieldValue type, but give an any type would be good enough.

  • Related (not duplicate): https://stackoverflow.com/questions/32968332/how-do-i-prevent-the-error-index-signature-of-object-type-implicitly-has-an-an/58347263#58347263 – Marijn May 24 '23 at 14:42
  • @Marijn I'm using this approach to treat the error, but I can't undestande why there is the error in this situation – DaniloMourelle May 24 '23 at 17:27

1 Answers1

0

Because typescript is complaining during compile time. When you are using in to check if a string is valid object key, it is doing it during run-time. As you might know, there is a difference between runtime and compile time. If you have used js, I think there would not be a problem, because it is not compiled language. You can do something like fieldName as keyof typeof someObject telling ts during compile time that this is a valid object key, but this approach has some drawbacks.

Rationalist
  • 116
  • 9
  • I not sure if I have all knowledge about the diff between them, but what I was expecting is if TS, in a union type can compute all key of a element of the union after checking a prop that distinguish it, it could accept to use a string as index after checking it exists. Couldn't this assumption be made at compile time? – DaniloMourelle May 24 '23 at 15:44
  • @DaniloMourelle did you define fieldName explicitly as a string? like const fieldName: string = 'someName'; – Rationalist May 24 '23 at 15:52
  • Yes, is come from a parameter with string type, the same for the object that come with its type – DaniloMourelle May 24 '23 at 16:00