Favorite way of dealing with typescripts `!`-forbidden warnings

For example, I often do:
const MiddleContainer: ParentComponent = (props) => {
const { isAuthenticated } = useAuthState()!;
const MiddleContainer: ParentComponent = (props) => {
const { isAuthenticated } = useAuthState()!;
I know my code is wrapped in an AuthContextProvider, and I want it to crash/error out in case I ever miss the context provider. How do you tell typescript-eslint to shut up about these cases?
3 Replies
Tommypop
Tommypop12mo ago
I think you can just throw if context is null in the useAuthState function
Bersaelor
Bersaelor12mo ago
Yes:
// if we forget to wrap AppContextProvider around our app, throw an error
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const useAppState = () => { return useContext(AppContext)! }
// if we forget to wrap AppContextProvider around our app, throw an error
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const useAppState = () => { return useContext(AppContext)! }
Tommypop
Tommypop12mo ago
export const useThemeContext = () => {
const ctx = useContext(ThemeContext);
if (!ctx) {
throw Error("No context found");
}
return ctx;
};
export const useThemeContext = () => {
const ctx = useContext(ThemeContext);
if (!ctx) {
throw Error("No context found");
}
return ctx;
};
This is what I use