Postgres enum in typeorm

Tai Tran picture Tai Tran · Jul 7, 2017 · Viewed 20.7k times · Source

In typeorm, how can I create a postgres enum type Gender as in this raw query

CREATE TYPE public.Gender AS ENUM (
    'male', 'female'
);
ALTER TABLE public.person ALTER COLUMN gender TYPE public.gender USING gender::gender;

and use it in the Entity class?

I have tried

@Entity()
export class Person {
    @Column('enum')
    gender: 'male' | 'female'
}

but obviously this isn't the right way, since I got the error message "type enum does not exist".

I don't want to use typescript enum either, since it will give me a bunch of 0s and 1s in the database.

Answer

Felipe Sabino picture Felipe Sabino · Jul 17, 2017

EDIT: This answer is still valid but a bit outdated as 0.1.0 alpha versions of TypeORM support enums for both PostgreSQL and MySQL.


PostgreSQL has a built in enum type, but unfortunately TypeORM currently only supports it for MySQL.

However, you could achieve a similar result with an int-type enum by using the @Column type as int and using the enum for your field type.

enum Gender {
  Male,
  Female,
  Other
}

@Entity()
export class Person {
    @Column('int')
    gender: Gender
}

(This approach lets you use the @IsEnum decorator from class-validator to validate the input if needed)

You could also use string enums (available on TypeScript 2.4, check Typescript `enum` from JSON string for older versions) and if that is the case just change the data type to string instead.

enum Gender {
  Male = 'male',
  Female = 'female',
  Other = 'other'
}

@Entity()
export class Person {
    @Column('text')
    gender: Gender
}