GithubHelp home page GithubHelp logo

sinclairzx81 / typebox Goto Github PK

View Code? Open in Web Editor NEW
4.3K 13.0 137.0 13.37 MB

Json Schema Type Builder with Static Type Resolution for TypeScript

License: Other

TypeScript 99.79% JavaScript 0.21%
json-schema typescript typecheck validate open-api ajv

typebox's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

typebox's Issues

Override TS types?

Is there a way to override what TS type is generated for a given type?

I'm using type-fest's Opaque type to distinguish between different "kinds" of primitives (e.g. strings that represent URLs). There doesn't currently seem to be a way to represent these in a typebox schema.

A possible API could look like this:

// from type-fest
type UrlString = Opaque<string, "url">;

// schema
const File = Type.Object({
  url: Type.Opaque<UrlString>(Type.String()),
  title: Type.String()
});
type File = Static<typeof File>; // { url: Opaque<string, "url">, title: string }

This wouldn't have to be tied to type-fest specifically. Type.Opaque could serve as a general escape-hatch to override the "natural" type. Maybe it could be renamed to avoid confusion.

CI/CD support

Hi @sinclairzx81 we at HospitalRun decided to base our data and db validation structure upon this library.

Would you mind if we make a PR to typebox to add GitHub actions for building and testing it automatically?

In addition to that, if you like also other automation as Coveralls or auto publish on npm just ping us.

how to default Type.Number to null

example
jobTitleId: Type.Optional(Type.Number())

when request body is
{
"industryGroupId": null
}
how can i defualt jobTitleId to null now it is 0

Disallow additional properties?

Hello, do you have any idea as to how I would disallow additional properties when validating?
I've read through ajv and found additionalProperties: false.

function TObject<T extends TProperties>(props: T, options?: CustomOptions) {
  return Type.Object<T>(props, { ...options, additionalProperties: false });
}

I've built my schema up to look like this:
const AttrObject = Type.Dict(AttributeValue);
Where AttributeValue is built up to look like this:
billede
Ignore the "value" key.

Validating against this should work, but I still get errors?

{
   "field1": { "type": "string"  }
}

Here's the raw json of the schema: https://pastebin.com/E1xwx1C5
And here are the errors I get: https://pastebin.com/iEYsekBH

Field descriptions

Is it possible to use typebox to generate JSON schemas with field descriptions?

For example:

"properties": {
    "productId": {
      "description": "The unique identifier for a product",
      "type": "integer"
    }
  }

[Feature Request] Add support for creating oneOf schema

Currently, I we can create anyOf and allOf schema with Union and Intersect. However, we are missing the oneOf schema.

Note. OneOf typing should be the same as anyOf.
For example:

const T = Type.Either([
  Type.String(),
  Type.Number()
])

type T = string | number

const T = {
  oneOf: [
    { type: 'string' },
    { type: 'number" }
  ]
}

Unable to set { additionalProperties: true } on Type.Object().

Hello! I recently bumped my version of typebox from 0.12.0 to latest, and since then I've lost the ability to set additionalProperties to true on an object type.

I've narrowed down the change in behavior from 0.14.1 -> 0.15.0.
Suspected commit: 2657b02

Here's is a minimal reproducible example:

const response = Type.Object({
payload: Type.Object({}, {additionalProperties: true})
})

console.log(JSON.stringify(response, null, 2))

Version 0.14.1
{ "type": "object", "properties": { "payload": { "additionalProperties": true, "type": "object", "properties": {} } }, "required": [ "payload" ] }

Version 0.15.0
{ "type": "object", "additionalProperties": false, "properties": { "payload": { "additionalProperties": false, "type": "object", "properties": {} } }, "required": [ "payload" ] }

make modifier property non-enumerable

heyho,

we're using typebox to generate json-schemas and some of them we pass to openapi generator. Some json-schema tools, like openapi generator don't like the fact that the typebox schemas contain the modifier property which isn't actually part of the json-schema spec.
So we wrote some "post-processing" step to remove these modifier properties before passing them to openapi, which "kinda" works but is a bit ugly.

Looking at typebox' code I understand why you need these properties, however I was wondering if you could make these non-enumerable or use a symbol as property name instead? Symbols aren't enumerable via normal means and also get dropped when JSON.stringify()-ing the schema.
This mean that systems like openapi generator wouldn't actually "see" these non-spec compliant properties.

Is that something that typebox could move to?

Usage with latest ajv leads to "unknown keyword kind"

ajv has released a new strict mode https://github.com/ajv-validator/ajv/blob/master/docs/strict-mode.md#strict-mode, and the example in the readme doesn't work. One should turn off the strict mode:

  const validate = new Ajv({ strict: "log" }).compile(PostSchema);

  const postData = {
    title: data.title,
    createdAt: data.createdAt,
    slug: data.slug,
    tags: data.tags,
    description: data.description,
    path: `/posts/${data.slug}`,
  };

  const isValid = validate(postData);
  if (!isValid) {
    console.error(validate.errors);
    throw new Error(`Invalid data found for post`);
  }

Union with Type.Undefined() produces any

Using Type.Undefined() in union always yields any

Screen Shot 2020-08-18 at 4 44 32 PM

I would expect mediaUrl to be a union of string | null | undefined, however I see any

TSC version: 3.8.3
Also thanks a lot for working on this project :)

Got error TS2315 with recently released TS 3.9

Hi,

I was using your great package on TS 3.8
I've just installed TS 3.9; since, the compiler complains about (mainly, but not only) this error:

error TS2315: Type 'Static' is not generic.

It might be due to this BC but i'm not sure: Type Parameters That Extend any No Longer Act as any

Right now I will stay on TS 3.8.

I don't know how I can help you more on this issue (except submitting a PR, but I don't know how to fix the issue right now)

Thanks,
Regards.

Error TS2315 with TSDX

I'm using TSDX with defaults settings and getting a TS2315


export const phoneInputValue = Type.Object({
  countryCode: Type.String(),
  isoCode: Type.String(),
  phone: Type.String(),
});

export type PhoneInputValueType = Static<typeof phoneInputValue>;

The error is :

@rollup/plugin-replace: 'preventAssignment' currently defaults to false. It is recommended to set this option to `true`, as the next major version will default this option to `true`.
@rollup/plugin-replace: 'preventAssignment' currently defaults to false. It is recommended to set this option to `true`, as the next major version will default this option to `true`.
โœ“ Creating entry file 1 secs
(typescript) Error: /home/edy/projectos/temp/prueba/src/index.ts(9,35): semantic error TS2315: Type 'Static' is not generic.
Error: /home/edy/projectos/temp/prueba/src/index.ts(9,35): semantic error TS2315: Type 'Static' is not generic.
    at error (/home/edy/projectos/temp/prueba/node_modules/rollup/dist/shared/node-entry.js:5400:30)
    at throwPluginError (/home/edy/projectos/temp/prueba/node_modules/rollup/dist/shared/node-entry.js:11878:12)
    at Object.error (/home/edy/projectos/temp/prueba/node_modules/rollup/dist/shared/node-entry.js:12912:24)
    at Object.error (/home/edy/projectos/temp/prueba/node_modules/rollup/dist/shared/node-entry.js:12081:38)
    at RollupContext.error (/home/edy/projectos/temp/prueba/node_modules/tsdx/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:17237:30)
    at /home/edy/projectos/temp/prueba/node_modules/tsdx/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:25033:23
    at arrayEach (/home/edy/projectos/temp/prueba/node_modules/tsdx/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:545:11)
    at Function.forEach (/home/edy/projectos/temp/prueba/node_modules/tsdx/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:9397:14)
    at printDiagnostics (/home/edy/projectos/temp/prueba/node_modules/tsdx/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:25006:12)
    at Object.transform (/home/edy/projectos/temp/prueba/node_modules/tsdx/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:29277:17)

Even with the plugin replace warming fixed the error apear.

lose types when exporting

Hi,
there is an issue when export the types (may be with Type.Union)

consider the following
module-a

import { Type, Static } from "@sinclair/typebox";

export const roleSchema = Type.Union([
  Type.Literal("ADMIN"),
  Type.Literal("MEMBER"),
]);
export const permissionSchema = Type.Union([
  Type.Literal("SUPERADMIN"),
  Type.Literal("CONTROLPANEL_ACCESS"),
]);
export const userSchema = Type.Object({
  uid: Type.String(),
  email: Type.String(),
  role: roleSchema,
  permissions: Type.Array(permissionSchema),
});

export type User = Static<typeof userSchema>

Inside module-a everything work fine, in fact

type User = {} & {} & {} & {
    uid: string;
    email: string;
    role: "ADMIN" | "MEMBER";
    permissions: StaticArray<TUnion<[TLiteral<"SUPERADMIN">, TLiteral<"CONTROLPANEL_ACCESS">]>>;
}

The issue is when we import the types into another module

module-b

import { User } from "module-a"
// we lose types
type User = {} & {} & {} & {
    uid: string;
    email: string;
    role: any;
    permissions: StaticArray<TUnion<TSchema[]>>;
}

Error: A rest element type must be an array type.

I have an issue with the lastest version 0.11.0:

node_modules/@sinclair/typebox/typebox.d.ts:6:17 - error TS2574: A rest element type must be an array type.

6     arguments: [...T];
                  ~~~~

node_modules/@sinclair/typebox/typebox.d.ts:11:17 - error TS2574: A rest element type must be an array type.

11     arguments: [...T];
                   ~~~~

and so on...

If I downgrade to 0.10.1, the error is not here.

Typescript version: 4.0.5

[Feature Proposal] Add extend function

Motivation

Working on complex schema can be tedious because of many common part repetitions.

Idea

It would be helpful to have something similar to this:

function extend<F, S>(firstSchema: F, secondSchema: S): F & S {
  if (firstSchema.type !== 'object' || secondSchema.type !== 'object') {
    throw new Error(`Only object schemas can be extended.`)
  }
  return {
    type: 'object',
    properties: {
      ...firstSchema.properties,
      ...secondSchema.properties,
    },
    required: (firstSchema.required || []).concat(secondSchema.required),
  }
}

Another example of this approach can be find here: https://github.com/fastify/fluent-schema/blob/master/src/ObjectSchema.js#L250

Example

export const channelSchema = Type.Object({
  channel: Type.String(),
  qapla: Type.Optional(
    Type.Object({
      apikey: Type.String(),
      callOn: Type.Union([Type.Literal('PACKING'), Type.Literal('SHIPPING')]),
      reference: Type.Union([Type.Literal('rifOrder'), Type.Literal('orderNumber')]),
    }),
  ),
})

const savedDocument = Type.Object({
  _id: ObjectId,
  tenantId: ObjectId,
  createdAt: Type.String({ format: 'date-time' }),
  modifiedAt: Type.String({ format: 'date-time' }),
  createdBy: ObjectId,
  modifiedBy: Type.Optional(ObjectId),
})

export const responseSchema = extend(savedDocument, channelSchema)

The nullable option is not reflected in TypeScript types

const NullableSchema = Type.Number({nullable: true})
type NullableSchemaType = Static<typeof NullableSchema>;
const test: NullableSchemaType = null;

results in:

error TS2322: Type 'null' is not assignable to type 'number'.

Is it even possible to fix this?

I realize that the recommended workaround is to use Type.Union() with Type.Null(), but this does not play well with some other libraries (among other reasons due to #37) and is actually considered an anti-pattern by some people: ajv-validator/ajv#1107 (comment)

Type.Object should turn additionalProperties to off by default

I think in most cases you would NOT want additionalProperties to be true (or omitted). I don't believe that there are many use cases that require additionalProperties to be true. In case you need it, you could still pass { additionalProperties: false } in the options. Since the conversion from Types to JSONSchema is not well-defined it may make sense to allow the user to configure these kinds of details themselves using a global config object.

Got typescript error when using with recently released TS 3.9 and fast-json-stringify

TS 3.9 and fast-json-stringify^2.0.0

import { Type } from '@sinclair/typebox';
import fastJson from 'fast-json-stringify';

enum Enum {
  A = 'A',
  B = 'B',
  C = 'C',
}
const schema = Type.Object({
  param1: Type.String(),
  enum: Type.Enum(Enum, { type: 'string' }),
});

const stringify = fastJson(schema);  // <=== this string doesn't pass ts type validation
stringify({});

Workaround:

const schema = Type.Object({
  param1: Type.String(),
  enum: {
    enum: Object.values(Enum),
    type: 'string',
  },
});

Intersection of an Object and Union

I was wondering if it was possible to do an intersection of an object and union.

interface BasicProps {
  id: string
  type: 'A' | 'B'
}
type Person = BasicProps & (
  {
    type: 'A'
    wallet: number
  } | {
    type: 'B'
    hat: string
  }
)

When I try doing a union inside of an intersect...

const Person = Type.Intersect([
    Type.Object({
        id: str(),
        type: Type.Union([Type.Literal('A'), Type.Literal('B')]),
    }),
    Type.Union([
        Type.Object({
            type: Type.Literal('A'),
            wallet: Type.Number(),
        }),
        Type.Object({
            type: Type.Literal('B'),
            hat: Type.String(),
        })
    ])
])

I get the error

Type 'TUnion<[TObject<{ type: TLiteral<"A">; wallet: TNumber; }>, TObject<{ type: TLiteral<"B">; hat: TString; }>]>' is not assignable to type 'TObject<TProperties>'.
  Type 'TUnion<[TObject<{ type: TLiteral<"A">; wallet: TNumber; }>, TObject<{ type: TLiteral<"B">; hat: TString; }>]>' is missing the following properties from type '{ kind: unique symbol; type: "object"; additionalProperties: false; properties: TProperties; required?: string[]; }': type, additionalProperties, properties

Is this possible to do with Typebox?

TTuple is not exported

I've run into this problem when using Type.Tuple() with this minimal example:

import { Type } from '@sinclair/typebox';

export const schema = Type.Tuple({});

The normal solution is providing a type definition to schema, but the main reason I'm using typebox is because types can be inferred.

Another solution would be exporting TTuple1 ... TTuple8 in typebox.d.ts.

null passes validation

Hi! Passing null to fields Type.String(), Type.Integer() or Type.Number() passes ajv validation on fastify.

Not sure how to fix it.

export const TBody = Type.Object({
    phoneNumber: Type.String(),
    timestampt: Type.Integer()
});

body: TBody
and POST request with

{
    phoneNumber: null,
    timestamp: null
}

NullKind is not defined

For version 0.12.7

Having a schema that includes Null(), e.g.

const schema = Type.Union([
  Type.Null(), 
  Type.string()
])

And calling my api that contains this schema, I get the error:
NullKind is not defined

Downgrading to 0.10.1 resolves the problem.

Type is not correctly inferred

This may be more of a question than an issue, but for some reason the type does not seem to be correctly inferred when I try this library:

const querySchema = Type.Object({
  page: Type.Integer({ default: 0, minimum: 0 }),
  page_size: Type.Integer({ default: 25, minimum: 1 }),
});

type TQuery = Static<typeof querySchema>;

image

image

In my example TQuery is pretty much useless :/
What am I doing wrong?
(tried with TS 3.9.7 and 4.0.2, in VSCode)

Supplying default values

Hello! First off, great project, looks like a really interesting idea! I stumbled across it completely by accident while browsing the typescript subreddit, and its exactly the kind of thing I've been looking for to plug into Fastify (currently I'm manually syncing TS definitions and Schemas)

I couldn't see any way of defining default values. Is this something that I missed, or that you're planning on supporting? For example, how would the follow translate into a Typebox definition?

timeout: {
  type: 'number',
  minimum: 1000,
  maximum: 15000,
  default: 5000,
}

It seems like Type.Range(1000, 15000) mostly covers it, but not the default handler

Typescript types not working on Static

Hi!

I was following the doc and I was hoping that the following statement would work:

import { Type, Static } from '@sinclair/typebox';

const ExampleType = {
  type: Type.Literal('location'),
  location: Type.Object({
    lat: Type.Number(),
    long: Type.Number(),
  }),
};
type ExampleType = Static<typeof ExampleType>;

function main(example: ExampleType) {
  example.type
}

main({ type: 'location', location: { lat: 1, long: 1 } })

But when I try to transpile with tsc, it gives me the following error:

$ npx tsc
index.ts:13:11 - error TS2339: Property 'type' does not exist on type 'unknown'.

13   example.type
             ~~~~

Found 1 error.

The IntelliSense doesn't recognize the ExampleType as a type as well.


Other informations:

package.json

  "dependencies": {
    "@sinclair/typebox": "^0.12.7"
  },
  "devDependencies": {
    "typescript": "^4.1.3"
  }

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "esnext",
    "module": "commonjs",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "skipLibCheck": true,
    "moduleResolution": "node",
    "outDir": "dist/",
    "resolveJsonModule": true,
    "experimentalDecorators": true,
    "sourceMap": true
  }
}

[Improvement] Usage of CHANGELOG

Hey ๐Ÿ‘‹,

Thank you for this awesome npm package! ๐Ÿ˜„
To ease the update of the dependency and clarify what changed between release, there should be a CHANGELOG.md file OR usage of GitHub releases with notable changes as description, this could be auto-generated, with strong commit convention.

See: https://keepachangelog.com/

'modifierSymbol' breaks type inferrance

When upgrading typebox from 0.9 to 0.10 I get the following error when using Type.Optional:

Exported variable has or is using name 'modifierSymbol' from external module ".../node_modules/@sinclair/typebox/typebox" but cannot be named, e.g. when defining

export const optionalStringType = Type.Optional(Type.String());

Usually the suggested fix is to define the type, but the whole reason I use typebox is that it can infer types.

Typebox JSONSchema definition / self-hosting

Apologies if this is more of a suggestion/question than an issue - but doubt it would get answered anywhere else.

I have a data type that would ideally contain a dynamic JSON schema definition - the only approaches I can see how to model this currently would be to either create a Typebox definition for a valid JSON Schema (which is hopefully possible, albeit a bit of work), create a sub-format that can be compiled into a JSON Schema, or just to use the Any type and lose strict typing...

The question I guess is whether JSON Schema would make sense as a base Typebox type to allow for handling of dynamic schemas, and if that is a project worth embarking on - or if the complexity would be too high to be considered feasible.

custom string formats?

Hey sinclairzx81,
Thanks for the awesome package. I'm having an issue adding custom string formats. The CustomOptions interface seems to indicate that you had in mind some way to do this, probably using delicious generics, but I was unable to sort it out. I've been basically hacking it with module augmentation:

import { CustomOptions } from '@sinclair/typebox';

declare module '@sinclair/typebox' {
  interface CustomOptions {
    format?: 'mongoId' | 'jwt';
  }
}

But this is bad. I've been trying to figure out the intended way to use Custom Options, but now I'm hungry and tired. Can you just tell me the answer? Thanks :)

Unknown type

Hi,

first thank you for this great tool!

Do you think it is possible do add the unknown type?

A way to merge with existing types

Firstly, I'm sorry if this is a newbie question. I'm a relatively new convert to typescript and still figuring my way around.

I'm currently using genql to generate a typescript lib from my GraphQL server. I'd like to import that definition into a typebox object (if this is even possible). Here's an example:

import { Static, Type } from '@sinclair/typebox'
import { currencies_enum } from '@data/hasura'

export type TBody = Static<typeof body>
const body = Type.Object({
  message: Type.String(),
  full_name: Type.String(),
  preferred_name: Type.String(),
  email: Type.String(),
  phone: Type.String(),
  password: Type.String(),
  currency: currencies_enum,
})

Where currencies_enum looks like this:

export type currencies_enum = 'AED' | 'AUD' | 'BRL' | 'CAD' | 'CHF' | 'CLP' | 'CNY' | 'CZK' | 'EUR' | 'GBP' | 'HKD' | 'IDR' | 'INR' | 'JPY' | 'KZT' | 'MOP' | 'MXN' | 'MYR' | 'NAD' | 'NGN' | 'NOK' | 'NZD' | 'PHP' | 'PKR' | 'PLN' | 'QAR' | 'RON' | 'RUB' | 'SAR' | 'SEK' | 'SGD' | 'THB' | 'TOP' | 'TRY' | 'TWD' | 'UAH' | 'USD' | 'VND' | 'VUV' | 'XAF' | 'ZAR'

Is there a function I can use to merge that currencies_enum type into the typebox representation? My primary reason for this is such that I can spit out a consistent typescript and json schema representation of the same type.

Thanks in advance. Any insight here would be a learning experience for me. ๐Ÿ™‡๐Ÿปโ€โ™‚๏ธ

Type.Any() is not working with Fastify response schmea

example

export const responseSchema = Type.Object({
  code: Type.Number(),
  subcode: Type.Number(),
  message: Type.String(),
  data: Type.Dict(Type.Any()) ,
})

Getting a error when reply send

const Controller: FastifyPluginCallback = (server, options, next) => {
  server.post(
    '/:moduleName/:action',
    {
      schema: {
        body: bodySchema,
        params: paramsSchema,
        response: {
          '2xx': responseSchema,
        },
      },
    },
    async (request, reply) => {
      reply.send({
        code: 0,
        subcode: 0,
        message: 'ok',
        data: {
          a: '123',
        },
      })
    }
  )
  next()
}
Error: Cannot coerce 123 to undefined

[email protected]
@sinclair/[email protected]

Error when Intersect objects with same key

Step to reproduce

const A = Type.Object({
      a: Type.String(),
})
const B = Type.Object({
      a: Type.String()
})
const T = Type.Intersect([A, B])

output

Error: schema is invalid: data/required should NOT have duplicate items (items ## 1 and 0 are identical)

generated schema

{
  type: 'object',
  kind: Symbol(ObjectKind),
  additionalProperties: false,
  properties: { a: { kind: Symbol(StringKind), type: 'string' } },
  required: [ 'a', 'a' ]
}

expected

{
  type: 'object',
  kind: Symbol(ObjectKind),
  additionalProperties: false,
  properties: { a: { kind: Symbol(StringKind), type: 'string' } },
  required: [ 'a' ]
}

optional properties?

Hi! It is possible to define an optional object property?

What I mean is something that, in Typescript, would be defined like b below:

type MyType = {
   a: string,
   b?: string 
}

In this case, a must be there but b may be absent.

We at first thought this could be defined with something like this, with typebox:

const MyTypeSchema = Type.Object({
   a: Type.String(),
   b: Type.Optional(Type.String())
})

But that's not quite the same. It leads to a type like this:

type MyType = {
   a: string,
   b: string  // <--- we'd want `b?: string`
}

Just wondering if we're missing something with respect to optional properties, or if the project does not allow them?

Thank you!
Dan

Is it possible to merge/modify typeboxes?

Hi

Is it possible to merge or somehow modify typebox?

For example:

const ModelInput = Type.Object({
  name: Type.String(),
});

const Model = Type.Object({
  id: Type.string(),
  ...ModelInput
})

Or vice-versa use some utility like pick/omit to modify it?

Thanks in advance

codegen from JSON Schema?

Wondering if there are any plans for this, and if not, would this be an interesting addition?

E.g. given a JSON Schema -> generate typebox definitions.

Type.Union() should result in anyOf instead of oneOf

This code:

const FirstSchema = Type.Object({foo: Type.String()})
const SecondSchema = Type.Object({foo: Type.String(), bar: Type.Optional(Type.String())})
const Union = Type.Union([FirstSchema, SecondSchema]);

Generates the following schema:

    {
      "oneOf": [
        {
          "type": "object",
          "properties": {
            "foo": {
              "type": "string"
            }
          },
          "required": [
            "foo"
          ]
        },
        {
          "type": "object",
          "properties": {
            "foo": {
              "type": "string"
            },
            "bar": {
              "type": "string"
            }
          },
          "required": [
            "foo"
          ]
        }
      ]
    }

The issue is that it uses oneOf instead of anyOf - oneOf means that objects may match exactly one schema, but in TypeScript, unions work like anyOf, not oneOf. With anyOf, objects must match at least one schema.

For example, this is valid TypeScript:

type FirstType = {
  foo: string;
}

type SecondType = {
  foo: string;
  bar?: string;
}

type UnionType = FirstType | SecondType;

const test: UnionType = {foo: "test"};

However, {foo: "test"} will not match the Union schema shown above, because:

JSON is valid against more than one schema from 'oneOf'.

Would you accept a PR that changes oneOf to anyOf for Type.Union()?

Utility Types: Partial, Required, Omit, Pick

It might be interesting to implement a subset of TypeScript's Utility Types. I expect this functionality would only apply to schemas of type TObject<Properties> and have the following behavior.

const Vector3 = Type.Object({
   x: Type.Number(),
   y: Type.Number(),
   z: Type.Number()
})

const PartialVector3 = Type.Partial(Vector3)         // { x?: number, y?: number, z?: number }

const RequiredVector3 = Type.Required(PartialVector3) // { x: number, y: number, z: number }

const Vector2 = Type.Pick(Vector3, ['x', 'y'])       // { x: number, y: number }

const Vector2 = Type.Omit(Vector3, ['z'])            // { x: number, y: number }

Having the ability to partial on a Type may help applications that use partial objects to update records in CRUD scenarios. Not having the ability to Partial<T> on a common type would lead to duplication of that type (one for Required and one for Partial). For consideration.

New version stopped working with Fastify schema validation

We are using Typebox for our Fastify schema validation. Example:

server.post<{ Body: NodeParams.RequestSetup }>(
  "/setup",
  { schema: { body: Type.Intersect([...]), response: {
    200: Type.Object({
      ...
    }), 
  } },
  async (request, reply) => {
    ...
  },
);

Getting this error on requests now:

node:258) UnhandledPromiseRejectionWarning: Error: schema is invalid: data.allOf[0].properties['meta'].properties['kind'] should be object,boolean
    at Ajv.validateSchema (/root/node_modules/ajv/lib/ajv.js:178:16)
    at Ajv._addSchema (/root/node_modules/ajv/lib/ajv.js:307:10)
    at Ajv.compile (/root/node_modules/ajv/lib/ajv.js:113:24)

Any idea what is going on?

A `TObject` With No/Optional-only Properties Has Invalid Static Type

I've come across an issue which I believe to be a bug in TypeBox (version 0.16.5) where a variable declared as a TObject, containing either all optional properties or no properties at all, becomes a top type that is assignable to anything except for undefined|null. I've provided a simple example below to demonstrate the issue. Is this type of behavior intended?

import { Static, Type } from "@sinclair/typebox";

let Test = Type.Object({
    key: Type.Optional(Type.Number()) // 
});

type TestType = Static<typeof Test>;

// Passes, but I don't believe it should...
let test: TestType = "this works";

Causing issues with latest Ajv

The new version of Ajv (v7) enables strict mode by default. This seems to break validation using typebox with these errors:

Error: strict mode: unknown keyword: "kind"
4128
      at Object.checkStrictMode (/root/node_modules/ajv/lib/compile/validate/index.ts:197:28)
4129
      at Object.checkUnknownRules (/root/node_modules/ajv/lib/compile/util.ts:27:22)
4130
      at checkKeywords (/root/node_modules/ajv/lib/compile/validate/index.ts:129:3)
4131
      at Object.validateFunctionCode (/root/node_modules/ajv/lib/compile/validate/index.ts:15:5)
4132
      at Ajv.compileSchema (/root/node_modules/ajv/lib/compile/index.ts:151:5)
4133
      at Ajv._compileSchemaEnv (/root/node_modules/ajv/lib/core.ts:659:24)
4134
      at Ajv.compile (/root/node_modules/ajv/lib/core.ts:323:34)

Is there some keyword being added to the schema for certain types under the hood?

LiteralKind is not defined when using fast-json-stringify

Type.Literal with Type.Union causes a ReferenceError error when using fast-json-stringify.

Type.Object({
  option: Type.Union([Type.Literal('pizza'), Type.Literal('salad'), Type.Literal('pie')]),
});
ReferenceError: LiteralKind is not defined
	at Object.$main (eval at build (/usr/src/app/.yarn/cache/fast-json-stringify-npm-2.2.9-c510e40cf5-f481a8e3e1.zip/node_modules/fast-json-stringify/index.js:158:20), <anonymous>:181:44)
	at serialize (/usr/src/app/.yarn/cache/fastify-npm-3.7.0-a75b1a843e-1a1d0d55eb.zip/node_modules/fastify/lib/validation.js:116:41)
	at preserializeHookEnd (/usr/src/app/.yarn/cache/fastify-npm-3.7.0-a75b1a843e-1a1d0d55eb.zip/node_modules/fastify/lib/reply.js:348:15)
	at next (/usr/src/app/.yarn/cache/fastify-npm-3.7.0-a75b1a843e-1a1d0d55eb.zip/node_modules/fastify/lib/hooks.js:198:7)
	at Object.<anonymous> (/usr/src/app/packages/tsi-core/src/plugins/replyCommonHeadersPlugin.ts:30:20)
	at next (/usr/src/app/.yarn/cache/fastify-npm-3.7.0-a75b1a843e-1a1d0d55eb.zip/node_modules/fastify/lib/hooks.js:202:34)
	at Object.<anonymous> (/usr/src/app/packages/tsi-core/src/plugins/replyResourcePlugin.ts:30:9)
	at next (/usr/src/app/.yarn/cache/fastify-npm-3.7.0-a75b1a843e-1a1d0d55eb.zip/node_modules/fastify/lib/hooks.js:202:34)
	at onSendHookRunner (/usr/src/app/.yarn/cache/fastify-npm-3.7.0-a75b1a843e-1a1d0d55eb.zip/node_modules/fastify/lib/hooks.js:216:3)
	at preserializeHook (/usr/src/app/.yarn/cache/fastify-npm-3.7.0-a75b1a843e-1a1d0d55eb.zip/node_modules/fastify/lib/reply.js:327:5)

Typebox version: 0.12.4

Recursive type support

I have some types which define recursive logical operations:

type Operator = 'and' | 'or';
type Operand = {
  name: 'operandA' | 'operandB' | 'operandC';
};
export type Condition = {
  operator: Operator;
  operands: Array<Condition | Operand>;
};

Which allows me to define a condition like this:

const condition: Condition = {
  operator: 'and',
  operands: [
    {
      name: 'operandA',
    },
    {
      operator: 'or',
      operands: [
        {
          name: 'operandB',
        },
        {
          name: 'operandC',
        },
      ],
    },
  ],
};

Which is equivalent to operandA and (operandB or operandC)

Is this representation currently possible with typebox?

Question: Enum and Unions

Hi, thanks for awesome project.

I have a question about union types and enums. We do not use ts enums because they are not supported in babel typescript. But for example such simple type:

type M = 'single' | 'married'

Could be expressed as:

{
type: 'string',
enum: ['single', 'married']
}

So that if i would write it like this with typebox:

const M = Type.Union([ Type.Literal('single'), Type.Literal('married') ])

/*
{
  kind: Symbol(UnionKind),
  anyOf: [
    { kind: Symbol(LiteralKind), type: 'string', enum: [Array] },
    { kind: Symbol(LiteralKind), type: 'string', enum: [Array] }
  ]
}
*/

so my suggestion is to allow to put union of literal values of the same type to be encoded as enum. WDYT?

Union of unions

Hi, it it possible to create a union of unions?

I tried doing the following

Type.Union([
  Type.Union([ ... ]),
  Type.Union([ ... ])
]);

but the static type is any.

My use case is a large union that I would like to break up into smaller unions. I suppose that increase the union size from 8 can also work but I'd rather compose the smaller unions.

Make use of $ref in JSON Schema

const Person = Type.Object({
  'name': Type.String(),
  'age': Type.Number()
});
const ChessMatch = Type.Object({
  'playerWhite': Person,
  'playerBlack': Person
});
console.log(JSON.stringify(ChessMatch));

outputs

{
  "type": "object",
  "properties": {
    "playerWhite": {
      "type": "object",
      "properties": {
        "name": {"type": "string"},
        "age": {"type": "number"}
      },
      "required": ["name","age"]
    },
    "playerBlack": {
      "type": "object",
      "properties": // same as above
// ...

This means, the definition of Person is repeated in the output. Instead, please consider using the $ref keyword. The output would then look something like this:

{
  "type": "object",
  "definitions": {
    "person": {
      "type": "object",
      "properties": {
        "name": {"type": "string"},
        "age": {"type": "number"}
      }
    }
  },
  "properties": {
    "playerWhite": {"$ref": "#/definitions/person"},
    "playerBlack": {"$ref": "#/definitions/person"}
  }
}

How to have an Object+Dict?

Hello, basically the desire here is to get the below type:

type Metadata = {
	provider: "gcs" | "s3"
	bucket: string
	name: string
	[key: string]: any
}

I've tried to do:

const Metadata = Type.Intersect(
	[
		Type.Dict(Type.Any()),
		Type.Object({
			provider: Type.Union([Type.Literal(`gcs`), Type.Literal(`s3`)]),
			bucket: Type.String({ minLength: 1 }),
			name: Type.String({ minLength: 1 }),
		})
	]
)

But it gives me an error on Type.Dict(Type.Any()),:

Type 'TDict<TAny>' is not assignable to type 'TObject<TProperties>'.
  Property 'properties' is missing in type 'TDict<TAny>' but required in type '{ kind: unique symbol; type: "object"; additionalProperties: false; properties: TProperties; required?: string[] | undefined; }'.ts(2322)
typebox.d.ts(78, 5): 'properties' is declared here.

Let me know if I have missed something!

Thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.