Object is possibly 'undefined'. During typescript array assignment and lookup

huangapple go评论82阅读模式
英文:

Object is possibly 'undefined'. During typescript array assignment and lookup

问题

当我尝试使用数组赋值或查找来访问数组中的变量时,我会得到一个 TypeScript 的 linting 错误,错误信息是 Object 可能是 'undefined'。我尝试检查操作中的所有变量是否都不是 undefined,但这并不起作用。以下是我的当前代码,它创建了一个二维数组的克隆,并将特定值设置为 true。

let start: [number, number] = [0, 0];

const visited: boolean[][] = Array.from({ length: rows }, 
                        () => Array(cols).fill(false));

visited[start[0]][start[1]] = true;

错误具体标记在 "visited[start[0]]" 上。此外,当我访问在我的 React 状态中定义的数组时,也会出现这个错误。

英文:

When I try accessing a variable in an array using array assignment or lookup I get a typescript linting error saying that Object is possibly 'undefined'.ts(2532). I try checking that all of the variables in the operation are not undefined yet that does not work. Here is my current code which creates a clone of a 2d array and sets a specific value to true.

let start: [number, number] = [0,0];

const visited: boolean[][] = Array.from<boolean[], boolean[]>({ length: rows }, 
                        () => Array<boolean>(cols).fill(false));

      
visited[start[0]][start[1]] = true;

The error specifically underlines "visited[start[0]]". Furthermore, this error occurs when I access an array defined in my react state.

答案1

得分: 1

此行为受编译器标志 noUncheckedIndexedAccess 控制。您似乎已经将其打开(我认为这是好事)。但这意味着每当您访问数组中的值时,TypeScript 都会告诉您该元素可能是 undefined,因为 TypeScript 无法确定数组的长度。

如果您只是希望访问该值,您应该使用评论中建议的可选链接运算符,如 visited[start[0]]?.[start[1]],如果 visited[start[0]] 不存在,它将返回 undefined

但是,如果您希望赋值,就不能使用这种方法(与评论中所说的相反),因为这可能导致语句 undefined = true,这是无效的。我会使用以下方法,确保 TypeScript 知道 row 实际上是存在的。

const row = visited[start[0]]
if (row) {
  row[start[1]] = true
}

这可能看起来有些繁琐,但这是为了更好的类型安全。

如果您只想要简单的方法,只需禁用 noUncheckedIndexedAccess,您的原始代码将正常工作。

英文:

This behavior is controlled with compiler flag noUncheckedIndexedAccess. You seem to have this turned on (which I think is good). But that means that any time you access a value in an array, TypeScript will tell you that the element might be undefined, since TypeScript never knows the length of an array.

If you simply wish to access the value, you should use the optional chaining operator as suggested in the comments, visited[start[0]]?.[start[1]], it will give you undefined if visited[start[0]] doesn't exist.

However if you wish to assign a value, you can't use that approach (contrary to what the comments say) since it would possibly end up in the statement undefined = true which is invalid. I'd use the following approach, where we ensure Typescript that row actually exist.

const row = visited[start[0]]
if (row) {
  row[start[1]] = true
}

This might seem cumbersome but it's for the greater good (of type safety).
If you however want the simple approach, just disable noUncheckedIndexedAccess and your original code will work.

huangapple
  • 本文由 发表于 2023年7月20日 12:35:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76726694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定