I encountered a type error in VS Code while working on this function. The error specifically points to board[0]
. It states that Object is possibly 'undefined'
.
export default function validPosition(board: Grid | Board, position: Position) {
const [row, col] = position
const numRows = board.length
const numCols = board[0]?.length
return row >= 0 && row < numRows && col >= 0 && col < numCols
}
In terms of zod validators and inferred types, I have the following:
export const cellValidator = z.object({
shown: z.boolean(),
flagged: z.boolean(),
mine: z.boolean(),
numNeighbors: z.optional(z.number().nonnegative()),
})
export const gridValidator = z.array(z.array(z.number()).min(1)).min(1)
export const boardValidator = z.array(z.array(cellValidator).min(1)).min(1)
export const positionValidator = z.tuple([
z.number().nonnegative(),
z.number().nonnegative(),
])
export type Cell = z.infer<typeof cellValidator>
export type Grid = z.infer<typeof gridValidator>
export type Board = z.infer<typeof boardValidator>
export type Position = z.infer<typeof positionValidator>
I am aware that the error message about board[0]
potentially being undefined is inaccurate. In actuality, board
is an array guaranteed to have at least one entry, which itself is an array containing numbers. This has been validated with zod.
export const gridValidator = z.array(z.array(z.number()).min(1)).min(1)
export const boardValidator = z.array(z.array(cellValidator).min(1)).min(1)
To resolve this issue, I found a few workarounds:
(board[0] as Cell[] | Array<number>).length
// or
board[0]!.length
// or
board[0]?.length
However, each of these solutions comes with its own set of challenges.
The main concern is that I shouldn't need to manually enforce correct types throughout my codebase when zod should handle this inference for me seamlessly. Why is the type checker raising doubts about board[0]
being defined when it is assuredly defined and validated by zod? What would be a cleaner, type-inference-friendly approach to manage this TypeScript error?