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

use satisfies instead of direct type for JSONSchema #1002

Merged
merged 2 commits into from Feb 1, 2024
Merged

Conversation

cyrilletuzi
Copy link
Owner

@cyrilletuzi cyrilletuzi commented Feb 1, 2024

TypeScript 4.9 introduced satisfies, which solves an old typing pain point for JSONSchema. Refer to the TypeScript documentation for an explanation.

Note it is just a documentation change, direct typing still works.

Below is an example from this library of the difference between direct typing and satisfies:

const schema1 = {
  type: "object",
  properties: {
    title: { type: "string" },
  },
  required: ["title"],
} satisfies JSONSchema;

schema1.properties.title; // OK!

const schema2: JSONSchema = {
  type: "object",
  properties: {
    title: { type: "string" },
  },
  required: ["title"],
};

schema2.properties.title; // Not OK
schema2.properties["title"]?.type; // OK, but type includes `undefined`

Note that there is still some type widening happening. The best solution would be:

const schema = {
  type: "object",
  properties: {
    title: { type: "string" },
  },
  required: ["title"],
} as const satisfies JSONSchema;

Thus the schema is kept fully intact, without any type widening, while still having autocomplete and type check.

@cyrilletuzi cyrilletuzi merged commit e223cd6 into main Feb 1, 2024
4 checks passed
@cyrilletuzi cyrilletuzi deleted the satisfies branch February 1, 2024 13:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant