我已经编写了一个定制钩子来旋转返回状态的二维数组Matrix:string[][],以及一个旋转该矩阵的函数roateMatrix:()=>void.当在组件中使用时,TypeScrip希望将‘Matrix’和‘rotateMatrix’同时引用为字符串[][]和()=>void的联合类型.

不幸的是,这意味着我不能访问‘Matrix’的索引,因为TypeScrip不能确定它是否真的是一个字符串[][],我不能调用‘rotateMatrix’,因为TypeScrip不能确定它是否真的是一个函数.

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

我的代码片段如下:

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];
}

Typescript相关问答推荐

类型断言添加到类型而不是替换

如何创建泛型类型组件来使用React Native的FlatList或SectionList?'

如果字符串文字类型是泛型类型,则用反引号将该类型括起来会中断

TS2339:类型{}上不存在属性消息

类型脚本映射类型:从对象和字符串列表到键值对象

如何实现异构数组内函数的类型缩小

为什么在leetcode问题的测试用例中,即使我确实得到了比预期更好的解决方案,这段代码也失败了?

如何将别名添加到vitest配置文件?

按函数名的类型安全类型脚本方法包装帮助器

在类型脚本中将泛型字符串数组转换为字符串字母并集

如何使这种一对一关系在旧表上起作用?

Typescript,如何在通过属性存在过滤后重新分配类型?

在打字应用程序中使用Zod和Reaction-Hook-Forms时显示中断打字时出错

如何避免多个类型参数重复?

内联类型断言的工作原理类似于TypeScrip中的断言函数?

来自枚举的<;复选框和组件列表

typescript如何从映射类型推断

如何正确键入泛型相对记录值类型?

必须从注入上下文调用Angular ResolveFn-inject()

如果父级被删除或删除,如何自动删除子级?