I have the following code in TypeScript:
import React, { useState } from "react";
export const AuthContext = React.createContext({
auth: {user: null},
setAuth: (auth: any) => {}
})
export const AuthContextProvider = (props: any) => {
const setAuth= (auth: any) => {
setState({...state, auth: auth})
}
const initState = {
auth: {user: null},
setAuth: setAuth
}
const [state, setState] = useState(initState)
return (
<AuthContext.Provider value={state}>
{props.children}
</AuthContext.Provider>
)
}
It works fine until I try to initialize initState = {auth: {user: "username", setAuth: setAuth}}
because I get the following error:
TS2322: Type '{ auth: { user: string; }; setAuth: (auth: any) => void; }' is not assignable to type '{ auth: { user: null; }; setAuth: (auth: any) => void; }'.
The types of 'auth.user' are incompatible between these types.
Type 'string' is not assignable to type 'null'.
20 |
21 | return (
> 22 | <AuthContext.Provider value={state}>
| ^^^^^
23 | {props.children}
24 | </AuthContext.Provider>
25 | )
How can I indicate auth.user
to be null or string?
CodePudding user response:
You can use the as
operator when you are creating the context to indicate that user
can be null
or string
.
export const AuthContext = React.createContext({
auth: { user: null as null | string },
setAuth: (auth: any) => {}
})