Description
Bug Report
🔎 Search Terms
noUncheckedIndexedAccess
string literal constant
🕗 Version & Regression Information
Introduced with noUncheckedIndexedAccess - present in all Typescript versions 4.1+
- This is the behavior in every version I tried, and I reviewed the FAQ for entries.
⏯ Playground Link
Playground link with relevant code
💻 Code
const LOOKUP_KEY = 'test';
function logNumber(val: number){
console.log(val);
}
function doStuff(input: {[key: string]: number}) {
if (input[LOOKUP_KEY]) {
logNumber(input[LOOKUP_KEY]); // Argument of type 'number | undefined' is not assignable to parameter of type 'number'
}
}
function doStuff2(input: {[key: string]: number}) {
if (input['test']) {
logNumber(input['test']); // Works as expected
}
}
function doStuffScopedConstant(input: {[key: string]: number}) {
const val = 'test';
if (input[val]) {
logNumber(input[val]); // Argument of type 'number | undefined' is not assignable to parameter of type 'number'
}
}
function doStuff3(input: Record<string, number>) {
if (input[LOOKUP_KEY]) {
logNumber(input[LOOKUP_KEY]); // Argument of type 'number | undefined' is not assignable to parameter of type 'number'
}
}
function doStuff4(input: Record<string, number>) {
if (input['test']) {
logNumber(input['test']); // Works as expected
}
}
🙁 Actual behavior
In doStuff
, doStuffScopedConstant
and doStuff3
, a compiler error is thrown, even though I've checked that a value exists for that index. When directly using a string literal inline (see other examples), this works as expected.
🙂 Expected behavior
All of the provided examples should compile cleanly. Having a stored constant string literal used as an index accessor should work the same way as using the literal in-place.
I suspect that the compiler logic for noUncheckedIndexedAccess
bails out w hen there's any variable used as an index accessor. I'd expect that if there's a const
that's also typed as a string literal, it should be treated the same way as using a string literal.