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
Natively make ajv validators typeguards in TS (integrate with json-schema-to-ts
)
#2091
Comments
Validate function is already typeguarded, you just need to pass the generic to it. |
Sorry I probably wasn't clear enough: I was talking about making validators typeguards without having to input the valid data type. I did not add a generic in my example code by purpose. If you define your schemas with the It may seem like a small difference, but it is a HUGE one! Providing manually the type of valid data:
Sure, you can always provide |
Overloads for compile should infer the type from the passed schema already - check this: https://github.com/ajv-validator/ajv/blob/master/lib/core.ts#L371 |
@epoberezkin Can you give me more context on the lines of code you provided ? It's not that easy to understand. It seems rather like the JSON schema type is inferred from the valid data type but I may be wrong 🤔 I think it would make more sense to infer the valid data type from the schema type as many schemas can represent the same type. |
it should work both ways - if you provide the schema of known type, the compiler would infer the type of data. There are actually tests for that. |
See this, for example - https://github.com/ajv-validator/ajv/blob/master/spec/types/json-schema.spec.ts Validating against the schema of known type proves the type of data |
@ThomasAribart |
What version of Ajv you are you using?
NA
What problem do you want to solve?
In TS, it would be neat to make
ajv.validate
andajv.compile
outputs typeguards.I maintain
json-schema-to-ts
which would allow such feature, as long as the schema is defined with theas const
statement. The lib is heavily tested againstajv
, and there are even examples on how to integrate withajv
.This is something that is frequently done in many projects, and it would be cool to have this feature natively in the lib.
What do you think is the correct solution to problem?
Some schemas (for instance, those imported from
json
files), will NOT be defined with theas const
statement. Besides,json-schema-to-ts
has impacts on IDE performances (it comes with some deeply nested type computations), andFromSchema
can accept configuration options such as deserialization patterns.So I think the best solution is to make such feature opt-in, but I'm not sure exactly how. Maybe with a type overload:
Will you be able to implement it?
Definitely yes.
Note: There are some other solutions out there, but I think
json-schema-to-ts
is the best for this need. Some links if you want to check them:ajv
)The text was updated successfully, but these errors were encountered: