Skip to content

Type of sibling property of a ref property is unknown when validated via JTDSchemaType #2167

Open
@ento

Description

What version of Ajv are you using? Does the issue happen if you use the latest version?

8.11.2 (latest as of this writing)

Ajv options object

import Ajv, { JTDSchemaType } from "ajv/dist/jtd";
const ajv = new Ajv();

JTD Schema

type MyType = {
  referenced: number;
  stringProp: string;
};

const schema: JTDSchemaType<MyType, { num: number }> = {
  definitions: {
    num: { type: "int32" }
  },
  properties: {
    referenced: { ref: "num" },
    stringProp: { type: "string" }
  }
} as const;

Sample data

const data = {} as any;

Your code

const validate = ajv.compile(schema);

if (validate(data)) {
  const revealType: never = data;
  const stringProp: string = data.stringProp;
  console.log(stringProp);
}

https://replit.com/@ento/IntrepidIndolentOutput#index.ts

^strictNullChecks is enabled in tsconfig.json

		"strictNullChecks": true, 

Validation result, data AFTER validation, error messages

TypeScript's typecheck errors:

// const revealType
Type '{ referenced: number; stringProp: unknown; } & {}' is not assignable to type 'never'.

// const stringProp
Type 'unknown' is not assignable to type 'string'.

What results did you expect?

The type of stringProp to be string after being narrowed by validate(data)

Are you going to resolve the issue?

My current workaround is to hold the definition in a const and use it to compose the schema object. (The actual code is a bit more complex than this.)

const numSchema = { type: "int32" } as const;

const schema: JTDSchemaType<MyType> = {
  properties: {
    referenced: numSchema,
    stringProp: { type: "string" }
  }
} as const;

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions