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

Argument of type '{}' is not assignable to parameter of type 'T | (() => T)' in React component with type parameter?

I am trying to do this:

function SomeComponent<T>({ children }: PropsType) {
  const [configuration, setConfiguration] = useState<T>({})
}

But I am getting:

Argument of type '{}' is not assignable to parameter of type 'T | (() => T)'

Here is a playground with my current code.

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

I would like the useState value to be a deeply nested object (with leaf nodes as nested objects, strings, numbers, nulls, or arrays, etc., basically a JSON object). I tried this, but same error:

function SomeComponent<T extends object>({ children }: PropsType) {
  const [configuration, setConfiguration] = useState<T>({})
}

How do I type this correctly?

>Solution :

import React, { useMemo, useState } from 'react'

type ConfigurationContextType = {
  configuration: Configuration
  setConfiguration: (config: object) => void
}

type Configuration = {
  darkMode?: boolean
}

export const ConfigurationContext =
  React.createContext<ConfigurationContextType>({
    configuration: {},
    setConfiguration: () => {},
  })

export function ConfigurationProvider({ children }: PropsType) {
  const [configuration, setConfiguration] = useState<Configuration>({})

  const value = useMemo(
    () => ({
      configuration,
      setConfiguration,
    }),
    [configuration, setConfiguration],
  )

  return (
    <ConfigurationContext.Provider value={value}>
      {children}
    </ConfigurationContext.Provider>
  )
}

type PropsType = {
  children: React.ReactNode
}

You do not need to use generic.

I made a Configuration type and gave it to useState.

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