1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[React] useCallbackで作られる関数に対してgenericを使いたい

Posted at

問題

import React from "react"
interface Props {}

interface CallbackProps {
  a: number
  b: string
}

interface CallbackReturn {
  c: boolean
}

const Test: React.FC<Props> = (props) => {
  const callback = React.useCallback<(props: CallbackProps) => CallbackReturn>(
    (props) => {
      const {a, b} = props
      
      return {
        c: true,
      }
    },
    []
  )

  const x = callback({ a: 1, b: "" })
  console.log('x.c:', x.c)

  return <></>
}
export default Test

Screen Shot 2021-06-11 at 10.16.07.png

Screen Shot 2021-06-11 at 10.24.24.png

useCallback自体にはgenericで型付けが出来るんだけど、ここで言うcallback変数となった関数にはgenericは渡せない。

callback<Generic>(...)  // こうしたい場合

解決

関数を返すuseMemoに切り替える。こうすることでdependencyも使え無駄に関数を生成することはないし、genericを渡せる関数にもなる。

import React from "react"
interface Props {}

interface CallbackProps<T> {
  a: T
  b: string
}

interface CallbackReturn {
  c: boolean
}



const Test: React.FC<Props> = (props) => {
  const callback = React.useMemo(() => function<T>(
    props: CallbackProps<T>
  ): CallbackReturn {
    const { a, b } = props

    return {
      c: true,
    }
  },
  [])

  const x = callback<boolean>({ a: false, b: "" })
  console.log('x.c:', x.c)

  return <></>
}
export default Test
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?