In TypeORM, you can use decorators to define entity properties and specify their data types. For fields of varchar and enum types, use the @Column decorator with appropriate parameters.
Here is an example of defining varchar and enum type fields in a TypeORM entity class:
typescriptimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; export enum UserRole { ADMIN = 'admin', EDITOR = 'editor', VIEWER = 'viewer', } @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column({ type: 'varchar', // specify field type as `varchar` length: 255, // specify field length nullable: false // field is not nullable }) username: string; // database field will be varchar(255) type @Column({ type: 'enum', // specify field type as `enum` enum: UserRole, // specify the enum type default: UserRole.VIEWER // set default value }) role: UserRole; // database field will be an enum type }
In this example, we define a User entity with a username field as varchar type, which is not nullable and has a maximum length of 255 characters. Additionally, we define a role field as enum type, where we specify the corresponding TypeScript enum using the enum option.
Note that when using enum type fields, database support for enum types may vary depending on the database system. In databases like MySQL and PostgreSQL, enum is a native type, but in others, it may be implemented differently or require using alternative types (such as varchar) to simulate enums.
Ensure all enum values are defined before running migrations, as adding or removing enum values may require manual schema modifications.