Search code examples
typescriptparsingenumsmigrationdatabase-migration

TypeORM does not parse Enum to the PostgreSQL type


Entity:

@Entity()
export class MyEntity {
  @Column({
    type: 'enum',
    enum: MyEnum,
    default: MyEnum.DEFAULT,
  })
  type: MyEnum;
}

Enum:

export enum MyEnum {
  DEFAULT = 1,
  NOT_DEFAULT = 2
}

Migration created by TypeORM:

await queryRunner.query(
  `CREATE TYPE "my_enum_type_enum" AS ENUM('1', '2')`,
);
await queryRunner.query(
  `ALTER TABLE "my_table" ADD "type" "my_enum_type_enum" NOT NULL DEFAULT '1'`,
);

Create the entity in code is working fine like the example below:

my_entity.type = MyEnum.DEFAULT; // "1" and "DEFAULT" does not work, but 1 (int) works

But when I try to save by the Repository I have an error:

invalid input value for enum my_enaum_type_enum: "DEFAULT"

What am I missing here?


Solution

  • Fixed following exactly the documentation: https://typeorm.io/#/entities/enum-column-type

    export enum MyEnum {
      DEFAULT = "default",
      NOT_DEFAULT = "not_default"
    }