Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Properties having type never when using oneOf #194

Open
jwasnoggin opened this issue May 14, 2024 · 0 comments
Open

Properties having type never when using oneOf #194

jwasnoggin opened this issue May 14, 2024 · 0 comments

Comments

@jwasnoggin
Copy link

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant