Search code examples
node.jspostgresqlormnestjstypeorm

Defining a Custom SQL Type in TypeORM for PostgreSQL


I'm utilizing TypeORM in my project, and I have a requirement to define a column with a custom SQL type, specifically 'datemultirange' in PostgreSQL. Unfortunately, TypeORM doesn't provide direct support for setting such a type. Are there any tools or workarounds available for achieving this?

Is there a method to specify a custom SQL type for a column in TypeORM that:

  • ensures consideration during table creation.
  • type checking when generating new migrations.

I would greatly appreciate any information on this matter. Thank you!

I try to find a way to set a custom type. Such a record is not supported:

@Column({ type: 'datemultirange' })

Solution

  • I found the answer to my question.

    If you want to set a type for a column that is not supported by TypeORM, you need to:

    1. Go to the configuration and expand "supportedDataTypes":

      const dataSource = new typeorm.DataSource(defaultOptions);
      dataSource.driver.supportedDataTypes.push('datemultirange');
      
    2. Set the required type in the metadata, in my case, it's "datemultirange"

      (TypeScript won't allow you to set it directly, so you'll have to disable type checking):

      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      @Column({ type: 'datemultirange' })
      ranges: string;
      
    3. Enjoy the new possibilities! =)