okzoomer
okzoomer

Reputation: 336

typescript string and numbered indices

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.

Upvotes: 1

Views: 112

Answers (1)

Tobias S.
Tobias S.

Reputation: 23825

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

Upvotes: 1

Related Questions