valtyr/prisma-kysely

Date not compatible with Timestamp

Closed this issue · 3 comments

Hi!

Thanks for this library, just found it but it's very useful. I might be doing something wrong but I'm having problems with Dates. I'm using postgress. I have a model in prisma:

model Device {
  serial              String     @id
  short_serial        String?
  application_version String?
  os_version          String?
  batch               String
  created_at          DateTime
  encryption          Boolean
  hardware            String
  name                String
  role                DeviceRole
}

Which generates kysely type:

import type { ColumnType } from "kysely";
export type Generated<T> = T extends ColumnType<infer S, infer I, infer U>
  ? ColumnType<S, I | undefined, U>
  : ColumnType<T, T | undefined, T>;
export type Timestamp = ColumnType<Date, Date | string, Date | string>;

....

export type Device = {
  serial: string;
  short_serial: string | null;
  application_version: string | null;
  os_version: string | null;
  batch: string;
  created_at: Timestamp;
  encryption: boolean;
  hardware: string;
  name: string;
  role: DeviceRole;
};

However a simple:

async getDevices(): Promise<Device[]> {
    return this.db
      .selectFrom('Device')
      .selectAll()
      .execute();
  }

Gives:

TS2322: Type '{ batch: string; serial: string; short_serial: string; application_version: string; os_version: string; created_at: Date; encryption: boolean; hardware: string; name: string; role: DeviceRole; }[]' is not assignable to type 'Device[]'.   Type '{ batch: string; serial: string; short_serial: string; application_version: string; os_version: string; created_at: Date; encryption: boolean; hardware: string; name: string; role: DeviceRole; }' is not assignable to type 'Device'.     Types of property 'creation_at' are incompatible.       Type 'Date' is missing the following properties from type 'Timestamp': __select__, __insert__, __update__

If I change it created_at to Date type everything works as expected.

Edit: For anyone else that might have this issue a workaround seems to be adding /// @kyselyType(Date) to the prisma schema for these fields.

Hey there @oscarthorn! Kysely table types aren't meant to be used directly in business logic. This is because their types can be complex, and differ based on operation (insert, update, select etc.). Kysely does however provide generics that help with this:

import {SelectType, InsertType, UpdateType} from 'kysely';

async getDevices(): Promise<SelectType<Device>[]> {
  return this.db
    .selectFrom('Device')
    .selectAll()
    .execute();
}

That being said in this case my advice would be to just remove the return type from the function and allow it to be inferred.

@valtyr Ah, thanks for the explanation!

Happy to help 😁