如何让TypeScript知道状态变量和setter函数是不同的类型,而不是联合类型(TS7053)



我已经编写了一个自定义钩子来旋转一个2d数组,该数组返回一个状态matrix:string[][]和一个旋转该矩阵的函数rotateMatrix:((=>无效的在组件中使用时,TypeScript希望将"matrix"one_answers"rotateMatrix"同时引用为字符串[][]和((=>的并集类型;无效的

不幸的是,这意味着我无法访问"matrix"的索引,因为TypeScript无法确定它确实是一个字符串[][],我也无法调用"rotateMatrix",因为TypeScript无法确定它是否是一个函数。

如何通知TypeScript自定义钩子返回的状态变量和函数是它们自己的确定类型?

我的代码片段:

type Matrix = (string | undefined) [][];
const testBoard: Matrix = [
['y', 'yx', 'y', 'yx', 'y', 'y', 'r', 'r'],
['y', 'y', 'y', 'y', 'y', 'y', 'r', 'rx'],
['o', 'o', 'o', 'o', 'y', 'yx', 'yx', 'y'],
['o', 'ox', 'ox', 'o', 'y', 'y', 'y', 'y'],
['g', 'gx', 'b', 'b', 'b', 'b', 't', 't'],
['gx', 'g', 'b', 'b', 'b', 'bx', 'tx', 't'],
['t', 't', 'b', 'bx', 'b', 'b', 't', 't'],
['tx', 't', 'b', 'b', 'bx', 'b', 't', 'tx']
];
function Board() {

const [board, rotateBoard] = useRotation(testBoard);
const [tiles, setTiles] = useState<TileProps[] | null>(null);
useEffect(() => {

const tileArr: TileProps[] = [];

for (let y=0; y < board[0].length; y += 2) {
for (let x=0; x< board.length; x += 2) {
const tile: TileProps = {
squares: [board[y][x], board[y][x+1], board[y+1][x+1], board[y+1][x]].join('_'),
row: y,
column: x,
gridRow: gridNumbers[y],
gridColumn: gridNumbers[x]
};
tileArr.push(tile);
}
}
setTiles(tileArr);
}, [board])
return (
<>
{ tiles
? <BoardFoundation onClick={rotateBoard}>
{tiles.map((tile: TileProps, index: number) => {
return <Tile key={index} squares={tile['squares']} row={tile.row} column={tile.column} gridRow={tile.gridRow} gridColumn={tile.gridColumn} />
})}
</BoardFoundation>
: null
}
</>
)
}
function useRotation( matrixNeedingRotation : Matrix ): ((Matrix | (() => void))[]) {
const [matrix, setMatrix] = useState<Matrix>(matrixNeedingRotation);
function rotateMatrix(): void {
const newMatrix = zip(...matrix);
setMatrix(newMatrix);
}

return [matrix, rotateMatrix];
}

非常感谢你的帮助。

使用元组作为函数的返回类型。它将如下所示:

function useRotation( matrixNeedingRotation : Matrix ): [Matrix, (() => void)] {
const [matrix, setMatrix] = useState<Matrix>(matrixNeedingRotation);
function rotateMatrix(): void {
const newMatrix = zip(...matrix);
setMatrix(newMatrix);
}
return [matrix, rotateMatrix];
}

相关内容

最新更新