简体   繁体   English

你如何让 TypeScript 知道 state 变量和设置器 function 是不同的类型而不是联合类型(TS7053)

[英]How do you let TypeScript know that the state variable and setter function are different types and not a union type (TS7053)

I've written a custom hook to rotate a 2d array that returns a state, matrix: string[][], and a function to rotate that matrix, rotateMatrix: () => void.我编写了一个自定义钩子来旋转一个二维数组,该数组返回一个 state、矩阵:string[][] 和一个 function 来旋转该矩阵,rotateMatrix:() => void。 When used in a component, TypeScript wants to refer to both 'matrix' and 'rotateMatrix' as a union type of both string[][] and ()=> void.在组件中使用时,TypeScript 希望将 'matrix' 和 'rotateMatrix' 都称为 string[][] 和 ()=> void 的联合类型。

Unfortunately, this means that I cannot access the indices of 'matrix' because TypeScript can't be sure it is indeed a string[][], and I can't call 'rotateMatrix' because TypeScript can't be sure it is indeed a function.不幸的是,这意味着我无法访问“矩阵”的索引,因为 TypeScript 不能确定它确实是一个字符串 [][],我不能调用“旋转矩阵”,因为 TypeScript 不能确定它确实是一个 function。

How do I inform TypeScript that the state variable and function returned by a custom hook are their own definite types?如何通知 TypeScript 自定义挂钩返回的 state 变量和 function 是它们自己的确定类型?

Snippet of my code:我的代码片段:

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

Thank you very much for your help.非常感谢您的帮助。

Use a tuple as the return type of the function.使用元组作为 function 的返回类型。 It's going to be like the following:它将如下所示:

function useRotation( matrixNeedingRotation : Matrix ): [Matrix, (() => void)] {

  const [matrix, setMatrix] = useState<Matrix>(matrixNeedingRotation);

  function rotateMatrix(): void {
    const newMatrix = zip(...matrix);
    setMatrix(newMatrix);
  }

  return [matrix, rotateMatrix];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何解决打字稿/反应错误 TS7053? - How do I solve typescript/react error TS7053? TypeScript 错误 7053 - 创建一个使用 prop 覆盖样式的自定义 React 组件,我如何正确告诉 TS 类型是什么? - TypeScript Error 7053 - Creating a custom React component that overrides styles with a prop, how do I properly tell TS what the type is? 元素隐式具有“任何”类型,因为“任何”类型的表达式不能用于索引类型“{ 1:元素; 2:元素; 3:元素; }'。 TS7053 - Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ 1: Element; 2: Element; 3: Element; }'. TS7053 TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{用户名:字符串; email:字符串; - TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ username: string; email: string; typescript 和 reactjs:如何使用 map - 错误 ts(7053) - typescript and reactjs : how to use map - ERROR ts(7053) React/TypeScript:Context API 状态下的联合类型 - React/TypeScript: Union Types in state of Context API 如何让一个屏幕知道其他屏幕的状态 - How do I let a screen know other screen's state 在类型 '[] | 上找不到具有类型参数的索引签名'字符串' iCommits'.ts(7053) - No index signature with a parameter of type 'string' was found on type '[] | iCommits'.ts(7053) 如何将 state 变量声明为 Typescript 上的类型 - How to declare a state variable as a Type on Typescript 在 Typescript 中,如果事先不知道对象的属性,您如何键入它? - In Typescript, how do you type an object when it's properties are not know beforehand?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM