Home > Back-end >  typescript string and numbered indices
typescript string and numbered indices

Time:10-22

In JS, array[0] and array['0'] return the same value. Similarly Object.hasOwn(array, '0') and Object.hasOwn(array, 0) both return true.

How to stipulate a type, that allows both number and string indices to an array?

If I use keyof Array<T> it returns error message "Cannot assign to 'length' because it is a read-only property." And if I use keyof Uint8Array, the typed array I'm using, additional "read-only" errors are returned.

If I use string | number the error is "Element implicitly has an 'any' type because index expression is not of type 'number'"

Of course I can just set it to string and then Number() but recently learning ts so wondering if there is another way.

CodePudding user response:

You would declare it like this:

let index: number | `${number}`

index can now be any number or any string which can be converted to a number.


Playground

  • Related