mafintosh/is-my-json-valid

Properties having type `never` when using oneOf

Opened this issue · 0 comments

Say I have the following validation function which takes an object which can have a property that is either a string or a string array, but always returns an object with that property as a string:

import jsonValidator from 'is-my-json-valid';

function getValidBody(body: unknown): { name: string } {
  const validator = jsonValidator({
    type: 'object',
    properties: {
      name: {
        oneOf: [
          { type: 'string' },
          { type: 'array', items: { type: 'string' } }
        ]
      }
    },
    required: ['name']
  });

  if (!validator(body)) {
    throw new Error();
  }

  if (Array.isArray(body.name)) {
    body.name = JSON.stringify(body.name); // error TS2322: Type 'string' is not assignable to type 'never'.
  }

  return body;
}

const body = getValidBody({ name: [] });
console.log(body);

After the validation is done, body.name has a type of never, but it should be string | string[]. This causes two issues:

  1. As in the example above, if you try to assign anything to body.name it gives an error
  2. If I remove the if (Array.isArray(body.name)) block, the function will happily return an object of type {name: string[]} (although it considers it to be {name: never}), which contradicts the declared return type.