-
-
Notifications
You must be signed in to change notification settings - Fork 145
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
JSON parser that never throws #1053
Comments
You have to specify the generic argument. Recommend to utilize the callback function in that case. |
Thanks for your reply, @samchon. It makes sense that the generic argument must be specified. What do you mean by the callback function? I can't find anything about callbacks in the documentation. Also, which issue is this a duplicate of, since you added the |
import typia, { tags } from "typia";
interface IMember {
id: string & tags.Format<"uuid">;
name: string;
age: number &
tags.Type<"uint32"> &
tags.Minimum<20> &
tags.ExclusiveMaximum<100>;
}
const safeParse =
<T>(parser: (input: string) => T) =>
(str: string): T | null => {
try {
return parser(str);
} catch {
return null;
}
};
console.log(
safeParse(
typia.json.createAssertParse<IMember>(),
)(
typia.json.stringify(
typia.random<IMember>(),
),
),
); Here it is. |
Thanks! |
When using
json.isParse
when data on the client, there is no guarantee that the data is valid JSON, since the user may have tampered with it. In such cases,json.isParse
throwsSyntaxError
. This makes typia cumbersome to use, since I have to handle exceptions when all I want to know is whether the data parses to the correct type. When the data is not parsable it does not parse to the correct type, so I would expect the function to just returnnull
in such cases.This would be a breaking change, so I suggest either adding a parameter to
isParse
or creating a separatesafeParse
that returnsnull
when an error is thrown.For example:
I tried just making this helper function, but then I get a warning:
[vite] warning: @rollup/plugin-typescript TS(typia.json.assertParse): non-specified generic argument.
Seems like I can't use typia with generics?The text was updated successfully, but these errors were encountered: