Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify error clarification types #2304

Merged
merged 1 commit into from
Feb 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 10 additions & 16 deletions src/frontend/src/components/authenticateBox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,24 +290,18 @@ type FlowError =
| ApiError
| RegisterNoSpace;

// Type machinery to allow translating error code (e.g. kind: "authFail") using the actual data
// contained in the error objects (e.g. authFail: (authFail: AuthFail) => ...).
type ErrorKind = FlowError["kind"]; // all known error tags for FlowError

// Look up an error type from an error kind, i.e.:
// type AssociatedError<"authFail"> = AuthFail
type AssociatedError<K extends ErrorKind> = {
[P in K]: { kind: P } & KindToError[P];
}[K];
// Maps all errors kinds to their error types (without kind field):
// { authFail: { ...fields of AuthFail with kind...}, badPin: ... }
// This seems to be a necessary step while looking up the error, otherwise typescript
// fails: 'Expression produces a union type that is too complex to represent.'
type KindToError = { [P in ErrorKind]: Omit<FlowError & { kind: P }, "kind"> };
// KindToError<'authFail'> = { ...fields of AuthFail with kind...};
// The 'Omit' seems to be a necessary step while looking up the error, otherwise typescript
// thinks the types conflict
type KindToError<K extends FlowError["kind"]> = Omit<
FlowError & { kind: K },
"kind"
>;

// Makes the error human readable
const clarifyError: {
[K in FlowError["kind"]]: (err: AssociatedError<K>) => {
[K in FlowError["kind"]]: (err: KindToError<K>) => {
title: string;
message: string;
detail?: string;
Expand Down Expand Up @@ -347,8 +341,8 @@ const clarifyError: {
}),
};

const clarifyError_ = <K extends keyof KindToError>(
flowError: AssociatedError<K>
const clarifyError_ = <K extends FlowError["kind"]>(
flowError: KindToError<K> & { kind: K }
): Omit<ErrorOptions, "primaryButton"> =>
clarifyError[flowError.kind](flowError);

Expand Down
Loading