我有一個字符串值,我打算將它用作數組的索引。我確信這個值,并希望斷言它是一個有效的“索引值”,在運行時將其轉換為數字或斷言它是數字(b/c它不是數字)。
所以我有:
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);
當前tsc
次投擲
Element implicitly has an 'any' type because index expression is not of type 'number' (tsserver 7015)
我寧愿不做這樣的事情:
//just because it's not a number
const v = inputEl.value as unknown as number;
有更好的方法嗎?非常感謝。
只是不要使用輸入
.value
字符串。使用它的.valueAsNumber
。