Skip to content

Commit 9c5112c

Browse files
authored
Add documentation for schemas in TypeScript (#89)
When defining JSON schemas in TypeScript, you will receive a compilation error unless you cast the schema object with `as const`. Related issue: #39
1 parent e171ced commit 9c5112c

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

README.md

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ import { Validator } from "express-json-validator-middleware";
3232
/**
3333
* Define a JSON schema.
3434
*/
35-
const addressSchema = {
35+
const addressSchema = {
3636
type: "object",
3737
required: ["street"],
3838
properties: {
@@ -69,6 +69,29 @@ app.post("/address", validate({ body: addressSchema }), (request, response) => {
6969

7070
Coming from `express-jsonschema`? Read the [migration notes](docs/migrating-from-express-jsonschema.md).
7171

72+
### Schemas in TypeScript
73+
74+
If you are writing JSON schemas in TypeScript, you will need to cast your schema
75+
to the `const` type e.g.
76+
77+
```typescript
78+
const addressSchema = {
79+
type: "object",
80+
required: ["street"],
81+
properties: {
82+
street: {
83+
type: "string",
84+
}
85+
},
86+
} as const;
87+
```
88+
89+
This is required so that TypeScript doesn't attempt to widen the types of values
90+
in the schema object. If you omit the `as const` statement TypeScript will raise
91+
a compilation error. The discussion in
92+
[this issue](https://github.com/simonplend/express-json-validator-middleware/issues/39)
93+
provides further background.
94+
7295
## Error handling
7396

7497
On encountering invalid data, the validator will call `next()` with a

0 commit comments

Comments
 (0)