Matching on custom type #94
-
Hi and thanks for a well made and useful library! I'm quite new to TypeScript, but stumbled upon a case where I had to extract an error message from different places in the error depending on its type, and the resulting "if-statement-hell" led me to look for a cleaner solution... Trying to implement ts-pattern on the situation, but can't figure out how to use a custom type I made in of the patterns. Probably missing something simple, as I suspect this isn't that unusual of a case! Here are how the errors could look: I tried following an example from the documentation, but got warnings when I tried to use my custom type: |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
After adding some formatting to your code, and then some filler types, this what I have: type FetchBaseQueryError = unknown;
type SerializedError = unknown;
type ToolsLambdaError = unknown;
export type MyError = {
id: string;
statusCode: number;
title: string;
detail: string;
};
export type RTKQueryError =
| Exclude<FetchBaseQueryError, { status: number; data: unknown }>
| { status: number; data: { message: string | MyError } };
export const setErrorInfoByPattern = (error: RTKQueryError | SerializedError) =>
match(error).with({ data: { message: ToolsLambdaError } }); The problem here, reported by TypeScript, is "'ToolsLambdaError' only refers to a type, but is being used as a value here." The best I can suggest, given my limited knowledge of the rest of your system, is to create a typeguard // Prefer something better than unknown. A union of possible types or something.
function isToolsLambdaError(val: unknown): val is ToolsLambdaError {
// Do checks here...
}
export const setErrorInfoByPattern = (error: RTKQueryError | SerializedError) =>
match(error).with({ data: { message: P.when(isToolsLambdaError) } }); |
Beta Was this translation helpful? Give feedback.
After adding some formatting to your code, and then some filler types, this what I have:
The problem here, reported by TypeScript, is "'ToolsLambdaError' only refers to a type, but is being used …