TSC throws an error that is inserted as a comment into the code.
tsconfig:
"noUncheckedIndexedAccess": true
type Tfactors = [number, number, number, number];
export default function changeEnough(pocket: Tfactors, bill: number): boolean {
const coinToDolarFactors: Tfactors = [0.25, 0.1, 0.5, 0.01];
let pocketTotal = 0;
for (let i in pocket) {
if (pocket[i] !== undefined && coinToDolarFactors[i] !== undefined) {
//Object is possibly 'undefined'.ts(2532)
pocketTotal += pocket[i] * coinToDolarFactors[i];
}
}
return pocketTotal >= bill;
}
To resolve this issue, I made the following changes:
type Tfactors = [number, number, number, number];
export default function changeEnough(pocket: Tfactors, bill: number): boolean {
const coinToDolarFactors: Tfactors = [0.25, 0.1, 0.5, 0.01];
let pocketTotal = 0;
for (let i in pocket) {
const pocketValue = pocket[i];
const factor = coinToDolarFactors[i];
if (pocketValue !== undefined && factor !== undefined) {
pocketTotal += pocketValue * factor;
}
}
return pocketTotal >= bill;
}
I am still learning TypeScript and wondering if there is a more efficient solution to this problem without declaring variables like pocketValue
and factor
, and without using !
to bypass TSC errors.