question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Required field in schema gets type 'string | undefined'

See original GitHub issue

I’m trying to validate an input and assign it to a variable of a type that I’ve defined. All fields are required in the validator. However, when I try to assign the validated input I get this error:

Type 'ObjectFromSchema<{ prop1: { type: "string"; required: true; }; }, never>' is not assignable to type 'Body'.
  Types of property 'prop1' are incompatible.
    Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not assignable to type 'string'.ts(2322)

Since the attribute prop1 is required, why is it showing as possibly undefined?

Demonstration code (the error is at the line which says const validBody: Body = body;):

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

type Body = { prop1: string };

function validateBody(body: any): Body {
    const bodyValidator = validator({
        type: 'object',
        required: true,
        properties: {
            prop1: {
                type: 'string',
                required: true as true
            }
        }
    });

    if (!bodyValidator(body)) {
        throw new Error('Invalid format: ' + bodyValidator.errors);
    }

    const validBody: Body = body;
    return validBody;
}

This is with is-my-json-valid version 2.20.5 and Typescript version 4.3.5, with "strict": true

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:6

github_iconTop GitHub Comments

1reaction
jwasnoggincommented, Jul 30, 2021

Amazing, that’s much better.

Definitely should update the readme!

0reactions
jwasnoggincommented, Oct 12, 2021

Got it to work using required: ['Label' as const]. I guess that’s a reasonable workaround, if not immediately obvious.

Note this also works for objects with multiple properties, eg

{
    type: 'object',
    properties: {
        name: { type: 'string' },
        value: { type: 'number' }
    },
    required: ['name' as const, 'value' as const]
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

how to validate JSON schema of return type String| undefined ...
First: Use proper type names in your schema (strings). You want to write a JSON schema. According to the definition, your type can...
Read more >
undefined treated as null able in JSONSchemaType #1375
Property 'nullable' is missing in type '{ type: "string"; }' but required in type '{ nullable: true; const?: undefined; enum?:
Read more >
Mongoose v6.8.2: Validation
Validators are not run on undefined values. The only exception is the required validator. Validation is asynchronously recursive; when you call Model#save, sub- ......
Read more >
Zod | Documentation
Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type, from a...
Read more >
Schema validation in TypeScript with Zod - LogRocket Blog
You might have encountered issues where you need to assign undefined or unknown to a type even after using its corresponding @types package...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found