-
-
Notifications
You must be signed in to change notification settings - Fork 112
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
Required field in schema gets type 'string | undefined' #184
Comments
Ah, const bodyValidator = validator({
type: 'object',
- required: true,
+ required: ['prop1'],
properties: {
prop1: {
type: 'string',
- required: true as true
}
}
}) We should update all the examples in the readme! |
Amazing, that's much better. Definitely should update the readme! |
I've now got a similar issue with a slightly more complex validator which has nested objects. Error:
Code: import jsonValidator from 'is-my-json-valid';
type Body = { StringProp: string, ObjectProp: { Label: string } };
function validateBody(body: any): Body {
const bodyValidator = jsonValidator({
type: 'object',
required: ['StringProp', 'ObjectProp'],
properties: {
StringProp: { type: 'string' },
ObjectProp: {
type: 'object',
required: ['Label'],
properties: {
Label: { type: 'string' }
}
}
}
});
if (!bodyValidator(body)) {
throw new Error('Invalid format: ' + bodyValidator.errors);
}
const validBody: Body = body;
return validBody;
} |
Hmmm, for some reason it seems like the Could you try to make the following change and see if it fixes it: const bodyValidator = jsonValidator({
type: 'object',
required: ['StringProp', 'ObjectProp'],
properties: {
StringProp: { type: 'string' },
ObjectProp: {
type: 'object',
- required: ['Label'],
+ required: ['Label'] as const,
properties: {
Label: { type: 'string' }
}
}
}
}); |
Same error message, except that |
Got it to work using 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]
} |
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:
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;
):This is with is-my-json-valid version 2.20.5 and Typescript version 4.3.5, with
"strict": true
The text was updated successfully, but these errors were encountered: