#Getting Types in Contexts

4 messages · Page 1 of 1 (latest)

quiet marsh
#

So, I have a Context like this.

#
  const content = children(() => props.children!);

  /// the local store.
  const [tokenStorage, setTokenStorage] = createLocalStorage({
    api: localStorage,
    prefix: "vista-auth-",
    deserializer: (data) => {
      if (!data || data == "undefined") {
        return "";
      }
      return data;
    },
    serializer: (value, _key, _options) => {
      return value;
    },
  });

  const [auth, setAuth] = createSignal<AuthState>({
    access: tokenStorage.access,
    refresh: tokenStorage.refresh,
  });

  // updates token storage.
  createEffect(() => {
    console.log("Updating token storage.");
    setTokenStorage("access", auth().access);
    setTokenStorage("refresh", auth().refresh);
  });
  const isAuthenticated = createMemo(() => {
    const hasAccessToken = auth().access.length > 0;
    const hasRefreshToken = auth().refresh.length > 0;
    return hasAccessToken || hasRefreshToken;
  });

  return (
    <AuthContext.Provider
      value={[
        auth,
        {
          refreshAuth: async () => {
            try {
              const tokens = await refreshTokens(auth().refresh);
              setAuth((_) => {
                return {
                  access: tokens.access_token,
                  refresh: tokens.refresh_token,
                };
              });
            } catch (e) {
              if (e instanceof UnauthorizedException) {
                setAuth((prev) => {
                  return {
                    access: "",
                    refresh: "",
                  };
                });
              }
            }
          },
          authenticated: isAuthenticated,
        },
      ]}
    >
      {content()}
    </AuthContext.Provider>
  );
};

export const useAuthContext = () => useContext(AuthContext);```
#

I thought i could enforce types by defining a type like so ```export interface AuthState {
access: string;
refresh: string;
}

type AuthContextValue = [
state: () => AuthState,
actions: {
refreshAuth: () => Promise<void>;
authenticated: Accessor<boolean>;
}
];

const AuthContext = createContext<AuthContextValue>();```

#

However, when I use the context in a child component, my editor is saying the types for "auth" and anything else is any. Is there a way I can enforce types?