ts报错Type 'number' has no call signatures.如何解决?

第一次用ts, 求指导
react创建自定义组件 使用导出方法时
ts报错
Not all constituents of type 'number | Dispatch<SetStateAction<number>>' are callable.
Type 'number' has no call signatures.

useCount:

    import * as React from 'react'

/**
 *
 * @param defaultCount
 * 自定义hooks
 */
const useCount = (defaultCount: number) => {
  const [count, setCount] = React.useState(defaultCount)
  const it: any = React.useRef()

  React.useEffect(() => {
    it.current = setInterval(() => {
      console.log('add...', count)
      setCount(() => count + 1)
    }, 1000)
  }, [])

  React.useEffect(() => {
    if (count >= 10) {
      clearInterval(it.current)
    }
  });
  return [count, setCount]
}

export default useCount

index.tsx

    import * as React from 'react'
import useCount from './useCount';

export default function index() {
  const [count, setCount] = useCount(3)
   // ts报错
  // This expression is not callable.
  // Not all constituents of type 'number | Dispatch<SetStateAction<number>>' are callable.
  //   Type 'number' has no call signatures.
  const add = () => setCount(0)
 
  return (
    <div>
      usecount: { count }
      <button onClick={add}>add</button>
    </div>
  )
}
阅读 19.7k
1 个回答

return [count, setCount] 返回的是 (number|Function)[] 不是你想要那個tuple類型.

你可以return ... as const (需要近期的ts版本) 或者手寫那個tuple.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题