在typescript中为dict键设置不同的类型



我在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>
)
}

它工作良好,直到我尝试初始化initState = {auth: {user: "username", setAuth: setAuth}},因为我得到以下错误:

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

如何指示auth.user为null或字符串?

在创建上下文时,可以使用as运算符来指示user可以是nullstring

export const AuthContext = React.createContext({
auth: { user: null as null | string },
setAuth: (auth: any) => {}
})

游乐场

最新更新