ThomasAribart / json-schema-to-ts

Infer TS types from JSON schemas 📝
MIT License
1.47k stars 31 forks source link

Does't work on deno? #47

Closed biluohc closed 2 years ago

biluohc commented 3 years ago

deno: 1.15.2

import Ajv from "https://esm.sh/ajv@8.6.3";

const schema = {
  type: "object",
  "properties": {
    "foo": { "type": "string" },
    "bar": { "type": "number", "maximum": 3 },
  },
  required: ["foo", "bar"],
} as const;
const schemaString = JSON.stringify(schema);
console.info(schemaString);

const validate = new Ajv().compile(schema);

const test = (obj: any) => {
  if (validate(obj)) console.log("Valid:", obj);
  else console.log("invalid!:", obj, validate.errors);
};

test({ "foo": "abc", "bar": 2 });
test({ "foo": "abc", "bar": 9 });
test({ "foo": "ab", "bar": "2" });

// https://github.com/ThomasAribart/json-schema-to-ts
import { FromSchema } from "https://deno.land/x/json_schema_to_ts@v1.6.5-beta.1/index.d.ts";
type FooBar = FromSchema<typeof schema>;
const forbar: FooBar = { "foo": "abc", "bar": "x" };
console.log(forbar);

The code running output as follow, but const forbar: FooBar = { "foo": "abc", "bar": "x" }; should not compile success?

{"type":"object","properties":{"foo":{"type":"string"},"bar":{"type":"number","maximum":3}},"required":["foo","bar"]}
Valid: { foo: "abc", bar: 2 }
invalid!: { foo: "abc", bar: 9 } [
  {
    instancePath: "/bar",
    schemaPath: "#/properties/bar/maximum",
    keyword: "maximum",
    params: { comparison: "<=", limit: 3 },
    message: "must be <= 3"
  }
]
invalid!: { foo: "ab", bar: "2" } [
  {
    instancePath: "/bar",
    schemaPath: "#/properties/bar/type",
    keyword: "type",
    params: { type: "number" },
    message: "must be number"
  }
]
{ foo: "abc", bar: "x" }
firstdorsal commented 2 years ago

similar problem here

ThomasAribart commented 2 years ago

Hi @biluohc @firstdorsal and thanks for reporting this issue.

I'm not familiar with deno but I'll look into it ASAP.

ThomasAribart commented 2 years ago

Hi @biluohc @firstdorsal ! Everything seems fine with v2.4.0:

-zsh 2022-05-11 14-40-00

Can you confirm so I can close this issue ?