[SOLVED] Set different types for a dict key in typescript

Issue

This Content is from Stack Overflow. Question asked by HuLu ViCa

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?



Solution

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) => {}
})

Playground


This Question was asked in StackOverflow by HuLu ViCa and Answered by Tobias S. It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?