如何设置"a useState function"的道具类型?

How to set props type of "a useState function"?

如何设置“一个 React useState 函数”的道具类型

// ParentComponent.tsx

import { useState } from "react"
import ChildComponent "./ChildComponent"

const ParentComponent = () => {
  const [prompt, setPrompt] = useState<boolean>(false)
  return <ChildComponent setPrompt={setPrompt}/>
}

// ChildComponent.tsx

interface ChildComponentProps {
  setPrompt: Function // ✅ WORKED but inaccurate!
  setPrompt: (value: boolean) => void // kinda WORKED thanks @acemarke!
  setPrompt: typeof React.useState //  DOESNT WORK!!!
}

const ChildComponent = (props: ChildComponentProps) => {
  return <button onClick={() => props.setPrompt(false)}>Button</button>
}

如果您在代码编辑器中将鼠标悬停在 setPrompt 上,您应该会看到类型:

Dispatch<SetStateAction<boolean>>

这些类型来自 React 内部。所以你要么想要导入它们:

import type { Dispatch, SetStateAction } from 'react'

Dispatch<SetStateAction<boolean>>

或者只使用 React 命名空间中的它们。

React.Dispatch<React.SetStateAction<boolean>>

这使得 ChildComponentProps 类似于:

interface ChildComponentProps {
  setPrompt: React.Dispatch<React.SetStateAction<boolean>>
}

Playground with no type errors