简体   繁体   中英

TypeScript declare type of useState hook as prop

I am trying to send props to a children and one of the props is the useState itself. If I declare the type as just Function I get an error about needing to be more specific and If I use void I get Expected 0 arguments, but got 1.

How do you declare the type for a setState hook?

app.tsx

import React, { useState } form 'react'
import Component from './component'

const App = () => {
 
  const [foo, setFoo] = useState>string>('')
 
  return (
    <Component 
      foo={foo}
      setFoo={setFoo}
    />
  )

}

component.tsx

import React, { FC } from 'react'

type Props  = {
  thing: string,
  setFoo: () => void // This fails I do not know how to declare the type for this, it takes a string
}

const Component: FC<Props> = ({ foo, setFoo}) => (
   <>
     <input onChange={e => setFoo(e.target.value} />
   </>
)

export default Component

setFoo is called with a string, as in setFoo("foo") . So the type is (_: string) => void . (The _ is just a placeholder variable name, you could also use a more detailed name like (foo: string) => void — it doesn't matter.)

The useState hook also allows functional updates . This is a way of avoiding problems when computing new state based on the previous state. To use this, you pass a function to the setter which receives the old value and returns the new value: setFoo((oldFoo) => oldFoo + "bar")

If you want your Component to be able to use functional updates as well, you'll need to include that in the type: (_: string | (oldValue: string) => string) => void .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM