Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
json-schema-to-ts
Advanced tools
The json-schema-to-ts npm package is a utility that converts JSON Schema definitions into TypeScript types. This allows developers to ensure type safety and consistency between their JSON data and TypeScript code.
Convert JSON Schema to TypeScript Types
This feature allows you to convert a JSON Schema into a TypeScript type. The `FromSchema` utility type takes a JSON Schema object and infers the corresponding TypeScript type.
import { FromSchema } from 'json-schema-to-ts';
const userSchema = {
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' },
age: { type: 'number' }
},
required: ['id', 'name']
} as const;
type User = FromSchema<typeof userSchema>;
const user: User = {
id: '123',
name: 'John Doe',
age: 30
};
Type Validation
This feature ensures that the TypeScript types derived from JSON Schema are validated at compile time, reducing runtime errors and improving code reliability.
import { FromSchema } from 'json-schema-to-ts';
const productSchema = {
type: 'object',
properties: {
productId: { type: 'string' },
price: { type: 'number' }
},
required: ['productId', 'price']
} as const;
type Product = FromSchema<typeof productSchema>;
const product: Product = {
productId: 'abc123',
price: 19.99
};
The typescript-json-schema package generates JSON Schema from your TypeScript types. It works in the opposite direction compared to json-schema-to-ts, which converts JSON Schema to TypeScript types. This package is useful if you start with TypeScript types and need to generate JSON Schema for validation or documentation purposes.
Ajv is a JSON Schema validator that can also generate TypeScript types from JSON Schema using additional plugins. While its primary focus is on validation, it offers similar functionality to json-schema-to-ts when combined with the appropriate plugins.
Zod is a TypeScript-first schema declaration and validation library. It allows you to define schemas in TypeScript and infer types from them. While it doesn't convert JSON Schema to TypeScript types directly, it provides a similar type-safe experience for defining and validating data structures.
If you use this repo, star it ✨
A lot of projects use JSON schemas for runtime data validation along with TypeScript for static type checking.
Their code may look like this:
const dogSchema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer" },
hobbies: { type: "array", items: { type: "string" } },
favoriteFood: { enum: ["pizza", "taco", "fries"] },
},
required: ["name", "age"],
};
type Dog = {
name: string;
age: number;
hobbies?: string[];
favoriteFood?: "pizza" | "taco" | "fries";
};
Both objects carry similar if not exactly the same information. This is a code duplication that can annoy developers and introduce bugs if not properly maintained.
That's when json-schema-to-ts
comes to the rescue 💪
The FromSchema
method lets you infer TS types directly from JSON schemas:
import { FromSchema } from "json-schema-to-ts";
const dogSchema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer" },
hobbies: { type: "array", items: { type: "string" } },
favoriteFood: { enum: ["pizza", "taco", "fries"] },
},
required: ["name", "age"],
} as const;
type Dog = FromSchema<typeof dogSchema>;
// => Will infer the same type as above
Schemas can even be nested, as long as you don't forget the as const
statement:
const catSchema = { ... } as const;
const petSchema = {
anyOf: [dogSchema, catSchema],
} as const;
type Pet = FromSchema<typeof petSchema>;
// => Will work 🙌
The
as const
statement is used so that TypeScript takes the schema definition to the word (e.g. true is interpreted as the true constant and not widened as boolean). It is pure TypeScript and has zero impact on the compiled code.
json-schema-to-ts
?If you're looking for runtime validation with added types, libraries like yup, zod or runtypes may suit your needs while being easier to use!
On the other hand, JSON schemas have the benefit of being widely used, more versatile and reusable (swaggers, APIaaS...).
If you prefer to stick to them and can define your schemas in TS instead of JSON (importing JSONs as const
is not available yet), then json-schema-to-ts
is made for you:
FromSchema
raises TS errors on invalid schemas, based on DefinitelyTyped's definitionsjson-schema-to-ts
only operates in type space. And after all, what's lighter than a dev-dependency?string
that you used instead of an enum
? Or this additionalProperties
you confused with additionalItems
? Or forgot entirely? Well, json-schema-to-ts
does!FromSchema
is extensively tested against AJV, and covers all the use cases that can be handled by TS for now*const addressSchema = {
type: "object",
allOf: [
{
properties: {
street: { type: "string" },
city: { type: "string" },
state: { type: "string" },
},
required: ["street", "city", "state"],
},
{
properties: {
type: { enum: ["residential", "business"] },
},
},
],
additionalProperties: false,
} as const;
But it is with FromSchema
!
type Address = FromSchema<typeof addressSchema>;
// => never 🙌
*If
json-schema-to-ts
misses one of your use case, feel free to open an issue 🤗
# npm
npm install --save-dev json-schema-to-ts
# yarn
yarn add --dev json-schema-to-ts
json-schema-to-ts
requires TypeScript 3.3+. ActivatingstrictNullChecks
or usingstrict
mode is recommended.
const fooSchema = {
const: "foo",
} as const;
type Foo = FromSchema<typeof fooSchema>;
// => "foo"
const enumSchema = {
enum: [true, 42, { foo: "bar" }],
} as const;
type Enum = FromSchema<typeof enumSchema>;
// => true | 42 | { foo: "bar"}
You can also go full circle with typescript enums
.
enum Food {
Pizza = "pizza",
Taco = "taco",
Fries = "fries",
}
const enumSchema = {
enum: Object.values(Food),
} as const;
type Enum = FromSchema<typeof enumSchema>;
// => Food
const primitiveTypeSchema = {
type: "null", // "boolean", "string", "integer", "number"
} as const;
type PrimitiveType = FromSchema<typeof primitiveTypeSchema>;
// => null, boolean, string or number
const primitiveTypesSchema = {
type: ["null", "string"],
} as const;
type PrimitiveTypes = FromSchema<typeof primitiveTypesSchema>;
// => null | string
For more complex types, refinment keywords like
required
oradditionalItems
will apply 🙌
const arraySchema = {
type: "array",
items: { type: "string" },
} as const;
type Array = FromSchema<typeof arraySchema>;
// => string[]
const tupleSchema = {
type: "array",
items: [{ type: "boolean" }, { type: "string" }],
} as const;
type Tuple = FromSchema<typeof tupleSchema>;
// => [] | [boolean] | [boolean, string] | [boolean, string, ...unknown[]]
FromSchema
supports the additionalItems
keyword:
const tupleSchema = {
type: "array",
items: [{ type: "boolean" }, { type: "string" }],
additionalItems: false,
} as const;
type Tuple = FromSchema<typeof tupleSchema>;
// => [] | [boolean] | [boolean, string]
const tupleSchema = {
type: "array",
items: [{ type: "boolean" }, { type: "string" }],
additionalItems: { type: "number" },
} as const;
type Tuple = FromSchema<typeof tupleSchema>;
// => [] | [boolean] | [boolean, string] | [boolean, string, ...number[]]
...as well as the minItems
and maxItems
keywords:
const tupleSchema = {
type: "array",
items: [{ type: "boolean" }, { type: "string" }],
minItems: 1,
maxItems: 2,
} as const;
type Tuple = FromSchema<typeof tupleSchema>;
// => [boolean] | [boolean, string]
Additional items will only work if Typescript's
strictNullChecks
option is activated
const objectSchema = {
type: "object",
properties: {
foo: { type: "string" },
bar: { type: "number" },
},
required: ["foo"],
} as const;
type Object = FromSchema<typeof objectSchema>;
// => { [x: string]: unknown; foo: string; bar?: number; }
FromSchema
partially supports the additionalProperties
and patternProperties
keywords:
additionalProperties
can be used to deny additional properties.const closedObjectSchema = {
...objectSchema,
additionalProperties: false,
} as const;
type Object = FromSchema<typeof closedObjectSchema>;
// => { foo: string; bar?: number; }
additionalProperties
and/or patternProperties
can be used to type unnamed properties.const openObjectSchema = {
type: "object",
additionalProperties: {
type: "boolean",
},
patternProperties: {
"^S": { type: "string" },
"^I": { type: "integer" },
},
} as const;
type Object = FromSchema<typeof openObjectSchema>;
// => { [x: string]: string | number | boolean }
properties
keyword, extra properties will always be typed as unknown
to avoid conflicts.const anyOfSchema = {
anyOf: [
{ type: "string" },
{
type: "array",
items: { type: "string" },
},
],
} as const;
type AnyOf = FromSchema<typeof anyOfSchema>;
// => string | string[]
FromSchema
will correctly infer factored schemas:
const factoredSchema = {
type: "object",
properties: {
bool: { type: "boolean" },
},
required: ["bool"],
anyOf: [
{
properties: {
str: { type: "string" },
},
required: ["str"],
},
{
properties: {
num: { type: "number" },
},
},
],
} as const;
type Factored = FromSchema<typeof factoredSchema>;
// => {
// [x:string]: unknown;
// bool: boolean;
// str: string;
// } | {
// [x:string]: unknown;
// bool: boolean;
// num?: number;
// }
For the moment, FromSchema
will use the oneOf
keyword in the same way as anyOf
:
const catSchema = {
type: "object",
oneOf: [
{
properties: {
name: { type: "string" },
},
required: ["name"],
},
{
properties: {
color: { enum: ["black", "brown", "white"] },
},
},
],
} as const;
type Cat = FromSchema<typeof catSchema>;
// => {
// [x: string]: unknown;
// name: string;
// } | {
// [x: string]: unknown;
// color?: "black" | "brown" | "white";
// }
// => Error will NOT be raised 😱
const invalidCat: Cat = { name: "Garfield" };
This may be revised soon now that
not
exclusions are now possible
const addressSchema = {
type: "object",
allOf: [
{
properties: {
address: { type: "string" },
city: { type: "string" },
state: { type: "string" },
},
required: ["address", "city", "state"],
},
{
properties: {
type: { enum: ["residential", "business"] },
},
},
],
} as const;
type Address = FromSchema<typeof addressSchema>;
// => {
// [x: string]: unknown;
// address: string;
// city: string;
// state: string;
// type?: "residential" | "business";
// }
const tupleSchema = {
type: "array",
items: [{ const: 1 }, { const: 2 }],
additionalItems: false,
not: {
const: [1],
},
} as const;
type Tuple = FromSchema<typeof tupleSchema>;
// => [] | [1, 2]
const primitiveTypeSchema = {
not: {
type: ["array", "object"],
},
} as const;
type PrimitiveType = FromSchema<typeof primitiveTypeSchema>;
// => null | boolean | number | string
In objects and tuples, the exclusion will propagate to properties/items if it can collapse on a single one.
// 👍 Can be propagated on "animal" property
const petSchema = {
type: "object",
properties: {
animal: { enum: ["cat", "dog", "boat"] },
},
not: {
properties: { animal: { const: "boat" } },
},
required: ["animal"],
additionalProperties: false,
} as const;
type Pet = FromSchema<typeof petSchema>;
// => { animal: "cat" | "dog" }
// ❌ Cannot be propagated
const petSchema = {
type: "object",
properties: {
animal: { enum: ["cat", "dog"] },
color: { enum: ["black", "brown", "white"] },
},
not: {
const: { animal: "cat", color: "white" },
},
required: ["animal", "color"],
additionalProperties: false,
} as const;
type Pet = FromSchema<typeof petSchema>;
// => { animal: "cat" | "dog", color: "black" | "brown" | "white" }
As some actionable keywords are not yet parsed, exclusions that resolve to never
are granted the benefit of the doubt and omitted. For the moment, FromSchema
assumes that you are not crafting unvalidatable exclusions.
const oddNumberSchema = {
type: "number",
not: { multipleOf: 2 },
} as const;
type OddNumber = FromSchema<typeof oddNumberSchema>;
// => should and will resolve to "number"
const incorrectSchema = {
type: "number",
not: { bogus: "option" },
} as const;
type Incorrect = FromSchema<typeof incorrectSchema>;
// => should resolve to "never" but will still resolve to "number"
Also, keep in mind that TypeScript misses refinment types:
const goodLanguageSchema = {
type: "string",
not: {
enum: ["Bummer", "Silly", "Lazy sod !"],
},
} as const;
type GoodLanguage = FromSchema<typeof goodLanguageSchema>;
// => string
const petSchema = {
type: "object",
properties: {
animal: { enum: ["cat", "dog"] },
dogBreed: { enum: Object.values(DogBreed) },
catBreed: { enum: Object.values(CatBreed) },
},
required: ["animal"],
additionalProperties: false,
if: {
properties: {
animal: { const: "dog" },
},
},
then: {
required: ["dogBreed"],
not: { required: ["catBreed"] },
},
else: {
required: ["catBreed"],
not: { required: ["dogBreed"] },
},
} as const;
type Pet = FromSchema<typeof petSchema>;
// => { animal: "dog"; dogBreed: DogBreed }
// | { animal: "cat"; catBreed: CatBreed }
FromSchema
computes the resulting type as(If ∩ Then) ∪ (¬If ∩ Else)
. While correct in theory, remember that thenot
keyword is not perfectly assimilated, which may become an issue in some complex schemas.
Since the introduction of template literal types with Typescript 4.1, the definitions
keyword seems implementable in json-schema-to-ts
.
I'll soon be looking into it. Meanwhile, feel free to open an issue 🤗
FAQs
Infer typescript types from your JSON schemas!
The npm package json-schema-to-ts receives a total of 1,859,512 weekly downloads. As such, json-schema-to-ts popularity was classified as popular.
We found that json-schema-to-ts demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.