Home > Back-end >  What is the question mark for next to TypeScript arg when its GraphQL arg indicates nullable true?
What is the question mark for next to TypeScript arg when its GraphQL arg indicates nullable true?

Time:02-20

// image.entity.ts

import { Field, ObjectType } from '@nestjs/graphql';
import {
  Column,
  DeleteDateColumn,
  Entity,
  PrimaryGeneratedColumn,
} from 'typeorm';

@ObjectType()
@Entity()
export class ImageEntity {
  @PrimaryGeneratedColumn('uuid')
  @Field(() => String)
  id: string; 

  @Column({ default: false })
  @Field(() => Boolean, { defaultValue: false }) 
  isThumbnail: boolean; 
//isThumbnail?: boolean;  // it worked without question mark
}
//image.resolver.ts

import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { ImageEntity } from './entities/image.entity';
import { ImageService } from './image.service';

@Resolver()
export class ImageResolver {
  constructor(private readonly imageService: ImageService) {}

  @Mutation(() => ImageEntity)
  async createImage(
    @Args('imageUrl') imageUrl: string,
  //=============this part=================
    @Args('isThumbnail', { nullable: true }) isThumbnail?: boolean, // <--- that question mark I'm takin bout
    // @Args('isThumbnail', { nullable: true }) isThumbnail: boolean, // it work fine without the question mark
// what this thing for?  
  //========================================
  ) {
    return await this.imageService.create({ isThumbnail, imageUrl });
  }
}

Like on the code, it linked with TypeORM and GraphQL. And some of args (also related columns) are nullable.

I got it that {nullable : true} made both args and columns of GraphQL and TypeORM doable without the question mark. It worked fine, but on the nestjs doc, the question mark was right below the

@Field(()=>Some Type, {nullable: true}.

My question is that the question mark is just to indicate it is optional as typescript type?

CodePudding user response:

Yes, it means that it's optional, see https://www.geeksforgeeks.org/why-use-question-mark-in-typescript-variable/

It is understandable that it seems to be superfluous, the reason for this is that on the one hand, GraphQL has to know that it's nullable and on the other, Typescript forces you to define your types strongly.

GraphQL can be used by "normal" Javascript as well, which is very much loose-typed, in that use-case the only place where the optional nature of the item would be specified is the nullable attribute.

  • Related