ThomasAribart / json-schema-to-ts

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

Inferred type is always `never` #93

Closed alphaone closed 1 year ago

alphaone commented 1 year ago

Hey,

I am trying the example for the README and I get never as the resulting type :\

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>;
// => Dog is never

I am using Typescript 4.8 on MacOS 12.6 and this is my package.json:

{
  "name": "fastify-ts-typeprovider-demo",
  "version": "0.0.1",
  "description": "",
  "main": "src/server.js",
  "scripts": {
    "start": "nodemon",
    "build": "swc ./src -d built"
  },
  "dependencies": {
    "json-schema-to-ts": "2.5.5"
  },
  "devDependencies": {
    "@swc-node/register": "1.5.4",
    "@swc/cli": "0.1.57",
    "@swc/core": "1.3.10",
    "@types/node": "18.11.3",
    "nodemon": "2.0.20",
    "typescript": "4.8.4"
  },
  "engines": {
    "npm": ">=7.0.0",
    "node": ">=18.11.0"
  }
}

Any idea, what I am doing wrong?

alphaone commented 1 year ago

When I define the schema without the required properties:

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;

then I will get a type with all undefined types:

type Dog = {
    [x: string]: unknown;
    name?: undefined;
    age?: undefined;
    hobbies?: [] | undefined;
    favoriteFood?: undefined;
}
alphaone commented 1 year ago

I found the problem.

I had

"noStrictGenericChecks": true,

for some reason in my tsconfig.json.

After removing this, everything works like expected.

ThomasAribart commented 1 year ago

Thanks @alphaone ! Will add it to the README !