Closed sceccotti89 closed 1 year ago
Looks like you need to set additionalProperties: false,
, along with the oneOf
.
@giraffesyo
Thanks for the response but it's still not working. This is the updated schema:
const catSchema = {
type: 'object',
additionalProperties: false,
oneOf: [
{
additionalProperties: false,
properties: {
name: { type: 'string' },
},
required: ['name'],
},
{
additionalProperties: false,
properties: {
color: { type: 'string', enum: ['black', 'brown', 'white'] },
},
},
],
}
I tried all the possible combinations (with and without additionalProperties
) but none of them worked.
Were you able to test it yourself and make it works?
I forgot to share details about my environment.
Hi @sceccotti89 !
Several elements here:
additionalProperties
at the root level will apply to an "invisible" properties: {}
keyword, and thus deny name
and color
property. The only valid data is { color?: undefined }
. You probably want to remove it.cat_property
is a union of two cases, A (name
) or B (color
). In your context, event if your cat
const has a name
property, it is typed as Cat
and TS will not take it for granted. Thus, when you try to access the name
property, TS still considers that it can be string
in case A or unknown
in case B. string
is a particular case of unknown
so unknown
wins.You can try not to assign the Cat
type to your cat
const but simply make sure it satisfies it:
// Will type-check cat against Cat type, but keep the "naturally inferred" cat type
const cat = { cat_property: { name: 'My name' } } satisfies Cat
Does that answer your issue ?
In a oneOf schema, the most nested property is not properly typed by TS.
Example:
If I hover over the Cat type, everything looks fine:
But when I try to access the name attribute, TS says it's unknown.
Is it a bug of the library or it's due to Typescript?