1

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.

1 Answer 1

1

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

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

2 Comments

Out of curiosity do you know if I also could have used regex?
It's not possible to use a regex at type level, only at runtime.

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.