TS Unchecked Indexed Access

Hey guys, I have a question about ts. I have a "noUncheckedIndexedAccess": true in my tsconfig. I am trying to make a function (well, chatgpt helped me create a function lol) that is a calculator to get Levenshtein distance (basically for a fuzzy search, but it's not the main point). as a part of it I have a for loop along the lines of this
const res: number[][] = [];
for (let i = 0; i < 10; ++i) {
res[i] = [];
res[i][0] = i;
}
const res: number[][] = [];
for (let i = 0; i < 10; ++i) {
res[i] = [];
res[i][0] = i;
}
So I get the error saying res[i] Object is possibly undefined. - on line
res[i][0] = i;
res[i][0] = i;
So my question is this: is there a way for compile to get it correctly as I literally define res[i] on the line before? or is it some sort of a bug on my part? or is it something not possible? P.S. if you are interested here's the full function
function levenshteinDistance(a: string, b: string): number {
const m = a.length;
const n = b.length;
const dp: number[][] = [];

for (let i = 0; i <= m; i++) {
dp[i] = [];
dp[i][0] = i;
}

for (let j = 1; j <= n; j++) {
dp[0][j] = j;
}

for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (a[i - 1] === b[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = Math.min(
dp[i - 1][j] + 1, // deletion
dp[i][j - 1] + 1, // insertion
dp[i - 1][j - 1] + 1 // substitution
);
}
}
}

return dp[m][n];
}
function levenshteinDistance(a: string, b: string): number {
const m = a.length;
const n = b.length;
const dp: number[][] = [];

for (let i = 0; i <= m; i++) {
dp[i] = [];
dp[i][0] = i;
}

for (let j = 1; j <= n; j++) {
dp[0][j] = j;
}

for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (a[i - 1] === b[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = Math.min(
dp[i - 1][j] + 1, // deletion
dp[i][j - 1] + 1, // insertion
dp[i - 1][j - 1] + 1 // substitution
);
}
}
}

return dp[m][n];
}
and I know I can cast types, but I want to do it without 'as ...'
3 Replies
bakdaddy
bakdaddyOP2y ago
bump
thevalorised
thevalorised2y ago
since res[i] is an object you can create another reference to it and check it with an if statement like
const refToInner = res[i];
if(refToInner) {
refToInner[0] = i;
}
const refToInner = res[i];
if(refToInner) {
refToInner[0] = i;
}
But I would recommend just pushing the values to the array instead of setting the items.
const res: number[][] = [];
for (let i = 0; i < 10; ++i){
res.push([i])
}
const res: number[][] = [];
for (let i = 0; i < 10; ++i){
res.push([i])
}
bakdaddy
bakdaddyOP2y ago
thanks, that's what I kinda thought, just make a new reference and check it
Want results from more Discord servers?
Add your server