Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

// ParentComponent.tsx

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

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

// ChildComponent.tsx

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

If you hover over setPrompt in your code editor you should see the type:

Dispatch<SetStateAction<boolean>>

Those types come from inside React. So you either want to import them:

import type { Dispatch, SetStateAction } from 'react'

Dispatch<SetStateAction<boolean>>

Or just use them from the React namespace.

React.Dispatch<React.SetStateAction<boolean>>

WHich makes ChildComponentProps something like:

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

Playground with no type errors

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading