Type error when using example with Typescript
grawtar opened this issue · 4 comments
I've tried the library and it works perfectly with normal js, but throws type errors when using ts.
The type error occurs at addressSchema
when passing it to body
. Is there something I missed?
Type '{ readonly type: "object"; readonly required: readonly ["number", "street", "type"]; readonly properties: { readonly number: { readonly type: "number"; }; readonly street: { readonly type: "string"; }; readonly type: { ...; }; }; }' is not assignable to type 'ValidateFunction | undefined'.
Type '{ readonly type: "object"; readonly required: readonly ["number", "street", "type"]; readonly properties: { readonly number: { readonly type: "number"; }; readonly street: { readonly type: "string"; }; readonly type: { ...; }; }; }' is not assignable to type 'JSONSchema7'.
Types of property 'required' are incompatible.
The type 'readonly ["number", "street", "type"]' is 'readonly' and cannot be assigned to the mutable type 'string[]'.
import express from "express";
import { Validator, ValidationError } from "express-json-validator-middleware";
const app = express();
app.use(express.json());
const addressSchema = {
type: "object",
required: ["number", "street", "type"],
properties: {
number: {
type: "number",
},
street: {
type: "string",
},
type: {
type: "string",
enum: ["Street", "Avenue", "Boulevard"],
},
},
} as const;
const { validate } = new Validator({});
app.post("/address", validate({ body: addressSchema }), (request, response) => {
response.send({});
});
app.listen(3000);
I have the same issue - as a workaround, you can use the AllowedSchema
, exported from the library, and remove as const
:
const addressSchema: AllowedSchema = {
@grawtar @olivierbeaulieu A couple of things will help me investigate this:
- Which version of
express-json-validator-middleware
are you using? - Please can you share the
tsconfig.json
you're using on the project where you see this error.
This issue is likely related to #39.
I'm using express-json-validator-middleware@2.2.1
And here's my config:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "commonjs",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react",
"noFallthroughCasesInSwitch": true
},
"include": ["./**/*.ts"],
"exclude": ["node_modules"]
}
@olivierbeaulieu Thank you!
After some discussion on Twitter I've learnt from @i-like-robots that your approach of using the AllowedSchema
type is the correct way to do this:
const addressSchema: AllowedSchema = {
I'm going to update the TypeScript part of the README to recommend this instead of as const
.