Sequelize-typescript: enum column

Created on 15 May 2017  Â·  4Comments  Â·  Source: RobinBuschmann/sequelize-typescript

@RobinBuschmann

How do I write an enum column?

enum RoleStatus { ACTIVE, DELETED, PENDING}

I want the default value to be pending

question

Most helpful comment

If you want to use the data type ENUM, you could implement it like this:

typescript @Default('ACTIVE') @Column(DataType.ENUM('ACTIVE', 'DELETED', 'PENDING')) state: 'ACTIVE'|'DELETED'|'PENDING';
Therefore you need to map your TypeScript enum values to its string representations. (RoleStatus[RoleStatus.ACTIVE]) or you're could use literal types instead:
typescript type RoleStatus = 'ACTIVE'|'DELETED'|'PENDING';
typescript @Default('ACTIVE') @Column(DataType.ENUM('ACTIVE', 'DELETED', 'PENDING')) state: RoleStatus;

(In TypeScript 2.4 string valued enums will be supported: https://github.com/Microsoft/TypeScript/pull/15486)

(Regarding enum types in databases in general it might be useful to read this http://stackoverflow.com/a/8792748)

All 4 comments

If you want to use the data type ENUM, you could implement it like this:

typescript @Default('ACTIVE') @Column(DataType.ENUM('ACTIVE', 'DELETED', 'PENDING')) state: 'ACTIVE'|'DELETED'|'PENDING';
Therefore you need to map your TypeScript enum values to its string representations. (RoleStatus[RoleStatus.ACTIVE]) or you're could use literal types instead:
typescript type RoleStatus = 'ACTIVE'|'DELETED'|'PENDING';
typescript @Default('ACTIVE') @Column(DataType.ENUM('ACTIVE', 'DELETED', 'PENDING')) state: RoleStatus;

(In TypeScript 2.4 string valued enums will be supported: https://github.com/Microsoft/TypeScript/pull/15486)

(Regarding enum types in databases in general it might be useful to read this http://stackoverflow.com/a/8792748)

thanks @RobinBuschmann I tried it and It worked perfectly!

How can it be done without duplication of the enum constants?

Found a solution:

Since I don't want to repeat enum constants, this is a solution:

export enum MyEnum {
  FIRST = 'FIRST',
  SECOND = 'SECOND',
  THIRD = 'THIRD',
}

…

  @Column({ type: DataType.ENUM({ values: Object.keys(MyEnum) }) })
  value: MyEnum;
Was this page helpful?
0 / 5 - 0 ratings

Related issues

JustGreg picture JustGreg  Â·  4Comments

YaroslavOsetrov picture YaroslavOsetrov  Â·  3Comments

KAMAELUA picture KAMAELUA  Â·  4Comments

lverledens picture lverledens  Â·  4Comments

samanmohamadi picture samanmohamadi  Â·  5Comments