I have a React Context where a function takes in another function as an argument. A generic hook then uses this.
// Context
export type A = { id: string }
const TestProvider = () => {
function test(doStuff: (a: A) => void) {...}
return <TestContext.Provider value={{test}}>{children}</TestContext.Provider>
}
// Hook
export function useThing<T extends A>() {
const { test } = useContext(TestContext)
const [stuff, setStuff] = useState<T[]>()
function doStuff(a: T) {
setStuff([...stuff, a])
}
function doMoreStuff() {
test(doStuff) // The error occurs here
}
}
I’ve looked at a lot of posts with this same problem, but they all have some sort of return value. How do I fix this for a function that returns nothing?
If I change the function signature in the hook to doStuff(a: Pick<T, 'id'>)
, the error disappears. However, this will cause an error in the setter function:
Type ‘T | Pick<T, “id”>’ is not assignable to type ‘T’.
‘T | Pick<T, “id”>’ is assignable to the constraint of type ‘T’, but ‘T’ could be instantiated with a different subtype of constraint ‘A’.