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