Closed jason-curtis closed 7 months ago
Hm. Explicitly specifying const mySchema: Schema = {...literal json...}
works though.
I.e. this works:
const a: Schema = { ... }
const b: Schema = a
And this errors:
const a = { ... }
const b: Schema = a
Isolated example:
type A = B[]
type B = { [id: string]: boolean }
const x: A = [
{ "X": true },
{ "Y": false }
]
const y = [
{ "X": true },
{ "Y": false }
]
const z: A = y // fails
If I'm reading this correctly, it seems like a typescript bug, then?
As a workaround, it looks like I can declare my schema in a .ts
file like so:
mySchema.ts
(instead of mySchema.json
)
import {Schema} from '@exodus/schemasafe';
const mySchema: Schema = {...schema goes here...};
export default mySchema;
then...
import mySchema from '@/schemas/mySchema'
import { validator } from '@exodus/schemasafe';
const myValidator = validator(mySchema); // no errors
I'm uncertain if this can be fixed on schemasafe side, yes.
And that workaround should work. I'll also test a JSON.parse variant shortly. see below
const s: Schema = JSON.parse("{...schema goes here...}');
also works, but typescript doesn't seem to provide any type validation in that case (at least by default).
Thanks. I'd really like to be able to just copy over my schema .json
file over from elsewhere and import it directly. For now I have this working with ajv
.
@jason-curtis Hm. I'm unsure if disabling ts typechecks for schemas would be a good solution to this.
yeah I don't think that would be a good option either. I'm able to work around the issue by casting to unknown
but I'm hoping to have type checking support.
Afaik ajv just works this around by not typechecking schemas except for certain top-level properties like $schema
...
I'll take another look
Hi, it seems to me that the typing for Schemas is too strict in a particular case. Please let me know if this is a bug in my code or yours:
Repro
There are a lot of things going on in my schema but here is a reduced example. If
propertyA
is 1, thenpropertyB
must be null. IfpropertyA
is 2, thenpropertyC
must be null. There are other properties present and validated at a higher level, but I'm leaving them out for this minimal example.side note: I know this particular rule set can be converted to use
oneOf
, but there are other rules in the real schema that makeallOf
more straightforward.From there, I'm just importing it and using
validator
:here's the full typescript error:
It seems like
schemasafe
expects the same properties to be named in each sub-schema, but I don't see why that would be the case.