Home > Back-end >  Setting null to optional parameters using TypeORM and MySQL database
Setting null to optional parameters using TypeORM and MySQL database

Time:07-18

I'm trying to create a graphql mutation to edit the account details of my app users. An account have fields for gender and birthday (optional fields). In my InputType I have:

@InputType()
export class UserEditAccountDetailsInput {
    @Field()
    email: string;
    @Field(() => String, { nullable: true })
    birthday?: string | null
    @Field(() => String, { nullable: true })
    gender?: string | null
}

And for the ObjectType:

@Field({ nullable: true })
@Column({ default: null })
gender?: string

@Field({ nullable: true })
@Column({ default: null, type: 'date' })
birthday?: string

I've tried in this way:

@Field({ nullable: true })
@Column({ default: null, type: 'date' })
birthday?: string | null

but I receive this error:

NoExplicitTypeError: Unable to infer GraphQL type from TypeScript reflection system. You need to provide explicit type for 'birthday' of 'User' class.

I've also tried to specify the type for birthday and gender like this:

@Field(() => String, { nullable: true })
@Column({ default: null, type: 'date' })
birthday?: string

but the issue wasn't fixed.

If I don't specify that " | null" on my ObjectType, it seems to work fine, but I have this TypeScript issue:

Types of property 'gender' are incompatible. Type 'string | null | undefined' is not assignable to type '(() => string) | QueryDeepPartialEntity<string | undefined>'.

Do you have any ideas about what I can do? Thank you!

CodePudding user response:

I implemented the same scenario but I didn't get an error. Maybe there is a problem with graphql versions. If you update the versions with the versions I will post below, you can solve the problem:

"graphql": "^15.3.0"
"type-graphql": "^1.1.1"
"@types/graphql": "^14.5.0"
"typescript": "^4.7.4"

By the way, there may also be an error with tscongif.json:

{
  "compilerOptions": {
    "baseUrl": "./src",
    "outDir": "./dist",
    "module": "commonjs",
    "target": "es2019",
    "lib": ["es6", "esnext.asynciterable"],
    "sourceMap": true,
    "allowJs": true,
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": false,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": false,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "types": ["node"],
    "resolveJsonModule": true
  },
  "exclude": [
    "node_modules",
    "build",
    "scripts",
    "acceptance-tests",
    "webpack"
  ]
}
  • Related