-1

I have a string value, which I intend to use as an index of an array. I'm sure of this value and want to assert that it's a valid 'index value', w/o converting it to a number at runtime or asserting it's a number (b/c it's not a number).

So I have:

const inputEl = window.document.getElementById('foo') as HTMLInputElement;
//it's indeed a string, I'm sure of it and have no squirm because of it
const v = inputEl.value as string;
const a = ['foo',];
const result = a[v];

console.log(result);

Currently tsc throws

Element implicitly has an 'any' type because index expression is not of type 'number' (tsserver 7015)

I'd rather not do something like:

//just because it's not a number
const v = inputEl.value as unknown as number;

Is there a better way to do it? Thank you.

3
  • A string can't be used as an array index. Array indexes are always numbers. If you want to use a string as key, you should use an object. Commented Nov 12, 2023 at 19:58
  • @jabaa does it mean that I must convert it to a number at runtime, like const num = Number(v); Commented Nov 12, 2023 at 20:00
  • 1
    TypeScript expects numbers as keys. JavaScript allows strings and implicitly converts them. I would explicitly convert the strings, avoid the implicit conversion and solve this problem. Commented Nov 12, 2023 at 20:02

1 Answer 1

1

Just don't use the input .value string. Use its .valueAsNumber.

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

Comments

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.