Search code examples
nestjstypeormnestjs-typeorm

Best way to assign default entity values in NestJS


I am new to NestJS and prefer to always work with Typescript's "strict": true compiler option. However when I do this a few of the auto-generated files throw errors due to no default values being set. For example I have this Entity file

organization.entity.ts

import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
import { OrganizationTypeEnum } from './organization-type.enum';

@Entity({ name: 'Organization' })
export class OrganizationEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  name: string;

  @Column({ default: null })
  logoUrl: string | null;

  @Column({ default: OrganizationTypeEnum.COBRAND })
  type: OrganizationTypeEnum;
}

Which gives an error like this for each property

Property id has no initializer and is not definitely assigned in the constructor.

What is the proper convention here? Should I:

  • assign a value directly like id: string = '';
  • give it a non-null assertion like id!: string;

Or is there something else I should do instead? Assigning a value feels wrong because I don't think that value would ever be used anywhere and it's potentially misleading. Perhaps strigc mode in typescript isn't worth it here?


Solution

  • The best solution would be to set the tsconfig option strictPropertyInitialization to false, for the sake of both your DTOs and your entities