Skip to content

Instantly share code, notes, and snippets.

@smonn
Last active June 28, 2022 15:59
Show Gist options
  • Save smonn/b5ecaf9c97eb28b567e55098ae886891 to your computer and use it in GitHub Desktop.
Save smonn/b5ecaf9c97eb28b567e55098ae886891 to your computer and use it in GitHub Desktop.
Reproduce issue with fast-json-stringify v5 and @sinclair/typebox
{
"name": "fjs-v5-typebox",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "ts-node src/index.ts"
},
"dependencies": {
"@sinclair/typebox": "0.23.5",
"fast-json-stringify": "5.0.3"
},
"devDependencies": {
"ts-node": "10.8.1",
"typescript": "4.7.4"
}
}
import { Type } from "@sinclair/typebox";
import Serializer from "fast-json-stringify";
const GuidSchema = Type.String({ format: "uuid", $id: "guid" });
const EmailSchema = Type.String({ format: "email", $id: "email" });
const IdSchema = Type.Union([GuidSchema, EmailSchema], {
$id: "id",
});
const BaseSchema = Type.Object(
{
name: Type.String(),
},
{ $id: "base" }
);
const SimpleSchema = Type.Object(
{
union: IdSchema,
},
{ $id: "simple" }
);
// Not using intersect seems to avoid the issue, but combined usage of
// intersect and union seems to throw the error below.
const Schema = Type.Intersect(
[
BaseSchema,
Type.Object(
{
union: IdSchema, // uncomment to trigger error
// guid: GuidSchema, // comment out if using above
},
{ $id: "inner_schema" }
),
],
{ $id: "schema" }
);
console.log(
Serializer(SimpleSchema)({
union: "4dbc3e7e-e8ac-53b9-ab91-5214e604f1bc",
})
);
// throws error if using IdSchema above
// no schema with key or ref "schema#/properties/id/anyOf/0"
console.log(
Serializer(Schema, {
// Cannot do this and use Type.Ref due to TS error
// schema: {
// union: IdSchema
// }
})({
name: "foo",
union: "7eb7fb5e-5947-50a7-961b-30e99bdd4d50",
guid: "7eb7fb5e-5947-50a7-961b-30e99bdd4d50",
})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment