Creating a Schema for an Inclusive Array Type in JsonSchema

Imagine you have the following type:

type oneOfTwoPossibleArrays = 
    | [1, 2]
    | [3, 4]

If you were to create a schema for it, what would it look like? This is my initial attempt that didn't work as expected:
<Edit: this code works with ajv: ^8.2.0. I used 7.2.6 when I opened this post.>

const schema: JSONSchemaType<oneOfTwoPossibleArrays> = {
    oneOf: [
        {
            type: 'array',
            minItems: 2,
            maxItems: 2,
            items: [{ type: 'number', const: 1 }, { type: 'number', const: 2 }]
        },
        {
            type: 'array',
            minItems: 2,
            maxItems: 2,
            items: [{ type: 'number', const: 3 }, { type: 'number', const: 4 }]
        }
    ]
}

Interestingly, defining only one of the arrays in the schema does not result in TypeScript errors:

const schema: JSONSchemaType<oneOfTwoPossibleArrays> = {
    type: 'array',
    minItems: 2,
    maxItems: 2,
    items: [{ type: 'number', const: 1 }, { type: 'number', const: 2 }]
}

Answer №1

Your solution is effective. You've identified a scenario where Ajv Typescript support struggles to compile your code:

// @ts-ignore.   // <<<<<----- INCLUDE THIS LINE
const schema: JSONSchemaType<oneOfTwoPossibleArrays> = {
    oneOf: [
        {
            type: 'array',
            minItems: 2,
            maxItems: 2,
            items: [{ type: 'number', const: 1 }, { type: 'number', const: 2 }]
        },
        {
            type: 'array',
            minItems: 2,
            maxItems: 2,
            items: [{ type: 'number', const: 3 }, { type: 'number', const: 4 }]
        }
    ]
}

Consider reporting this issue on the Ajv github issue tracker for resolution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the intention behind using the `(function(): Something{})` syntax?

(function() : Contract {…}). The code looked like an IIFE but then there was a colon, not what I expected. Was it meant to be a label? https://i.sstatic.net/wBYAT.png ...

The interface is incompatible with the constant material ui BoxProps['sx'] type

How can I make the interface work for type const material ui? I tried to register an interface for sx here, but it keeps giving me an error. import { BoxProps } from '@mui/material'; interface CustomProps { sx: BoxProps['sx&apo ...

Error: Unable to inject HttpClient dependency. Angular 5

I recently switched to using the Angular template in Visual Studio 2017 and decided to update to Angular 5.2. However, I encountered an error while trying to make a http call from the service class. The error message I received is: https://i.sstatic.net/p ...

How can you optimize the storage of keys in JS objects?

Just pondering over this scenario: Consider a line definition like the one below, where start and end are both points. let ln = { s: {x:0, y:0}, e: {x:0, y:0}, o: 'vertical' } Now imagine having a vast array of lines, how can we sav ...

The useEffect hook in React is signaling a missing dependency issue

Any tips on how to resolve warnings such as this one src\components\pages\badge\BadgeScreen.tsx Line 87:6: React Hook useEffect has a missing dependency: 'loadData'. Either include it or remove the dependency array react-hoo ...

ngx-datatables in Angular is experiencing issues with its filtering options

Having trouble implementing a filter option in ngx-datatables for all columns. I've written the code but it's not functioning correctly. Can anyone help me identify where I went wrong and find solutions? app.component.html: <label> Nam ...

Error: Trying to modify a property that is set as read-only while attempting to override the toString() function

I have a specific object that includes an instance variable holding a collection of other objects. Right now, my goal is to enhance this list of elements by adding a customized toString() method (which each Element already possesses). I experimented with t ...

Encountering data loss while mapping for the first time in React Native using useState - any solutions?

const initialData = [ { id: 1, name: `${accountList?.brideName} ${accountList?.brideSurname}`, type: 'Gelin', selected: false, tlText: accountList?.brideAccount?.accountTl, euroText: accountList?.brideAccou ...

Proper utilization of an interface with a literal object

I've been encountering some challenges with TypeScript. Let's say you have a literal object where the value is assigned using the spread operator: const defaultState = () => { return { profile: { id: '', displayName ...

When running ng build, the DefinitelyTyped package @types/async encounters issues

Previously, we built a website last year using the following versions: node v6.9.1 npm v3.10.8 angular-cli v1.0.0-beta.24 typescript v2.1.4 The application was successfully created by the previous developer. However, after setting up these versions and ...

What could be causing my Angular2 component to not properly use my template?

I have two components that I am working with. The first component is: import {Component} from 'angular2/angular2'; import {Navbar} from './navbar'; @Component({ selector: 'app' template: `<div class="col-md-12"> ...

Is it possible to define multiple regular expressions for a single field using yup in a form validation?

My goal is to validate an input to only accept URLs in Google Maps format. There are three possible valid outputs for a Google Maps URL: (for Google Maps app) (I only want to focus on ) (when sharing directly from Google Maps) Currently, I am able to ...

Would it be possible to use the Stripe customer portal to facilitate subscription upgrades or downgrades that take effect at the end of the current billing cycle?

I am struggling to figure out how to manage subscription upgrades and downgrades on the user interface side so that they start at the end of the current billing cycle. The only Stripe-hosted page for handling subscription changes is the customer billing p ...

Guide to effectively utilizing a lone boolean variable within Angular to dynamically manipulate various fields

Within my form, I have 10 text areas and 10 CKE editors. Initially, only the text areas are displayed upon loading. Each text editor has a toggle button located at the top. When this toggle function is called, the respective editor should switch to a CKE ...

Troubles encountered while fetching JSON data from an API in Angular

Currently, I am in the process of developing a website using the MEAN stack for a project. My focus is on handling the front end operations, specifically on retrieving and storing data from an API into an array for future use. However, I seem to be encount ...

What is the trick to maintaining the chiplist autocomplete suggestions visible even after inserting or deleting a chip?

After creating an autocomplete chiplist component in Angular, I noticed that when a user adds or removes an item, the suggestion list disappears and the input field is cleared. However, I would prefer to keep the autocomplete list open (or reopen it) so t ...

What is the method for expanding an object type using a string literal type?

I am encountering an issue with the code snippet below. In this code, type B is meant to extend type A by expanding the acceptable values for the property type. However, despite this intention, the assignment is resulting in a type error. type A = { ...

"Compile your code effortlessly in Netbeans with the TypeScript compiler for streamlined automation

My goal is to utilize Netbeans for NodeJS development with Typescript. Ideally, when I run a .ts file from Netbeans, it should automatically compile with the typescript compiler and then run the compiled .js file with NodeJS. However, I am encountering dif ...

Utilizing the subclass type as a parameter in inheritance

Looking for a way to restrict a function in C# to only accept classes of a specific base class type? In my current implementation, I have a base class (which can also be an interface) and n-classes that extend it. Here is what I am currently doing: abstr ...

Typescript custom sorting feature

Imagine I have an array products= [{ "Name":'xyz', 'ID': 1 }, { "Name":'abc', 'ID': 5 }, { "Name":'def', 'ID': 3 } ] sortOrder=[3,1,5] If I run the following code: sortOrder.forEach((item) =&g ...