打字稿和钩子

时间:2019-06-14 04:10:55

标签: reactjs typescript react-hooks

请问有人可以建议我使用Typescript将钩子转换为类型安全版本的最佳方法。这是一个简单的切换,可以在切换状态下显示不同的“事物”。

useToggle.js

const useToggleButton = ({on,off}) => {
  const [toggle, setToggle] = React.useState(false)

  const ToggleButton = () => (
    <div
      role="button"
      onClick={() => setToggle(!toggle)}
      data-testid="portal-toggle-btn"
    >
      {toggle? on : off}
    </div>
  )
  return [ToggleButton, toggle, setToggle]
}

问题是它返回一个带有组件,状态和setState函数的数组。我的尝试在下面,但出现错误

TS2605: JSX element type 'IReturnType' is not a constructor function for JSX elements.   Type 'IReturnType' is missing the
following properties from type 'Element': type, props, key

TS2739: Type '(boolean | Dispatch<SetStateAction<boolean>>)[]' is
missing the following properties from type 'IReturnType': component,
state, func

useToggle.tsx

import * as React from 'react'

interface IToggleBntProps {
  on: any
  off: any
}

interface IState {
  bol: boolean
}

interface IReturnType {
  component: React.FunctionComponent
  state: boolean
  func: (bol: boolean) => IState
}

const useToggleButton = ({ on, off }: IToggleBntProps): IReturnType => {
  const [toggle, setToggle] = React.useState(false)

  const ToggleButton = () => (
    <div
      role="button"
      onClick={() => setToggle(!toggle)}
      data-testid="portal-toggle-btn"
    >
      {toggle ? on : off}
    </div>
  )
  return [ToggleButton, toggle, setToggle]
}

export default useToggleButton

1 个答案:

答案 0 :(得分:1)

TypeScript实际上可以自动找出大多数这些类型!

在下面的代码中,在return语句末尾说as consta const assertion)可以让TypeScript正确地推断出您想要的返回类型:[() => JSX.Element, boolean, React.Dispatch<React.SetStateAction<boolean>>]

如果您想露骨,可以做type IReturnType = [() => JSX.Element, boolean, React.Dispatch<React.SetStateAction<boolean>>],但这是冗长且不必要的。

interface IToggleBntProps {
  on: any
  off: any
}

const useToggleButton = ({ on, off }: IToggleBntProps) => {
  const [toggle, setToggle] = React.useState(false)

  const ToggleButton = () => (
    <div
      role="button"
      onClick={() => setToggle(!toggle)}
      data-testid="portal-toggle-btn"
    >
      {toggle ? on : off}
    </div>
  )

  // saying 'as const' here means that TypeScript automatically
  // knows that this should be a tuple type of three elements.
  // Not you need TypeScript 3.4 or newer 
  return [ToggleButton, toggle, setToggle] as const;
}

export default useToggleButton