Optional columns in TypeORM

René Kulik on 30.01.2023

When working with TypeORM you might want to declare optional columns that do not have to be filled. An entity definition for such a use case might look like this:

@Entity()
class Foo {
  ...

  @Column({ nullable: true })
  bar?: string;
}

The entity Foo has a column bar which is optional. At first, this code seems sound and database entries can be created:

const foo = new Foo();
await repo.save(foo);

Now let’s try to update an existing entity by setting bar to undefined. The assumption is that the corresponding database value will be unset afterwards:

const foo = repo.findOne(...);
foo.bar = undefined;
await repo.save(foo);

Even though bar was set to undefined, the database value remains untouched. TypeORM is not designed to handle undefined values.

To address this, I suggest to make optional fields mandatory and to explicity define a null type. This prevents forgetting to set a field during an update. Adjust the column definition and the code to update an existing entity as follows:

bar: string | null;
const foo = repo.findOne(...);
foo.bar = null;
await repo.save(foo);