Encountering a type-safety problem while attempting to add data to a table with Drizzle

My database schema is structured like so:

export const Organization = pgTable(
    "Organization",
    {
        id: text("id").primaryKey().notNull(),
        name: text("name").notNull(),
        createdAt: timestamp("createdAt", { precision: 3, mode: "string" })
            .defaultNow()
            .notNull(),
        updatedAt: timestamp("updatedAt", {
            precision: 3,
            mode: "string",
        }).notNull(),
    },
    (table) => {
        return {
            name_key: uniqueIndex("Organization_name_key").using(
                "btree",
                table.name,
            ),
        };
    },
);

However, when attempting to execute a query on it:

import * as schema from "../src/drizzle/schema";
import { Client } from "pg";

export const client = new Client({
    connectionString: process.env.DATABASE_URL,
});

export const db = drizzle(client, { schema });

await db.insert(Organization).values({
    id: "68184833-8d03-41d6-95a2-4f23c4f097d6",
    name: "org",
    createdAt: new Date(),
    updatedAt: new Date(),
});

The error message in TypeScript states that the data is incorrect:

Object literal may only specify known properties, and 'id' does not exist in type '{ id: string | SQL<unknown> | Placeholder<string, any>; ...

When appending as any at the end, it resolves the issue. However, I prefer to maintain type safety. What am I missing here?

Answer №1

Based on the instructions in the Drizzle ORM insert documentation, it is necessary to specify a shape for the insert data:

type NewOrganization = typeof Organization.$inferInsert;

I was able to replicate your issue on stackblitz and found a solution. The error appears to be related to the date types, which should both be formatted as strings.

To resolve this, I recommend using .toISOString() (reference) so that the date is stored in the database as UTC without a specific timezone, as outlined in this guide.

Here is the corrected code snippet:

import * as schema from "../src/drizzle/schema";
import { Client } from "pg";

export const client = new Client({
    connectionString: process.env.DATABASE_URL,
});

export const db = drizzle(client, { schema });

type NewOrganization = typeof Organization.$inferInsert;

const newOrg: NewOrganization = {
  id: '68184833-8d03-41d6-95a2-4f23c4f097d6',
  name: "org",
  createdAt: new Date().toISOString(),
  updatedAt: new Date().toISOString(),
}

await db.insert(Organization).values(newOrg);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve a nested data type?

I am working with an interface named IFoo interface IFoo { name: string; version: number; init: (arg1: string, arg2: number) => Promise<string[]>; } I am interested in the type of init. Is there a way to extract it so that I can use this i ...

Hiding the line connector between data points in ChartJs

I recently took over a project that includes a line chart created using Chart.js by the previous developer. My client has requested that I do not display a line between the last two data points. Is this possible with Chart.js? I have looked through the doc ...

Exciting New Feature in WebStorm 2016.3: TypeScript Tooltips Inspired by VS Code!

One of the great features of Visual Studio Code is its excellent support for TypeScript, such as type inference displayed in tooltips. However, by default in WebStorm, only Console/Errors are visible in the tool window when hovering over a function without ...

Guide to creating a unit test for canActivate guard in Angular routing

Seeking guidance on writing a unit test for angular routing with the canActivate guard. Encountering an error when using the guard on routes, but no error is thrown without it. Would appreciate a suitable example along with an explanation. app-routing.mod ...

Encountering a Typescript issue with the updated Apollo server version within a NestJS application

After upgrading my nestJS application to use version 3.2 of apollo-server-plugin-base, I encountered two TypeScript errors related to a simple nestJS plugin: import { Plugin } from '@nestjs/graphql' import { ApolloServerPlugin, GraphQLRequest ...

Ways to classify the prop type of a functional component by specifying the different types of props for the FC

I have created two functional components that require different prop types. export interface OrderImageProps { orders: ICartItem[] } const OrderImage: React.FC<OrderImageProps> = (props: OrderImageProps) => { return ( <div> ...

What is the benefit of utilizing ngSubmit over just using a basic button and function?

Lately, I've been pondering whether to utilize ngSubmit or simply bind a (click)="submit()" on a button. There's been much debate about using submit and ngSubmit, but is it necessary to rely on the traditional HTML submit method? Particularly wh ...

You cannot use objects as valid children in React layout components

I encountered an issue with my layout: Unhandled Runtime Error Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead. The code in my DashboardLayout file (dashboardLa ...

Can dynamic string types be declared in Typescript?

Let's consider the following scenario: export enum EEnv { devint, qa1 }; export type TEnv = keyof typeof EEnv; export const env:Record<TEnv, {something:number}> = { devint: { something: 1, }, qa1: { something: 1, }, } Now, I ai ...

Employing strict mode, albeit with certain exceptions

When using the compiler strict mode ("strict": true), errors occur for my models that are structured like this: @Entity class MyModel { @Column() public name: string; @Column() public email: string; ... } The specific errors enc ...

What is causing the warnings for a functional TypeScript multidimensional array?

I have an array of individuals stored in a nested associative array structure. Each individual is assigned to a specific location, and each location is associated with a particular timezone. Here is how I have defined my variables: interface AssociativeArr ...

Customizing the main color scheme in Naive-UI with typescript

I am a beginner with Naive and I want to change the primary color of my app theme to orange. Initially, I used vuestic for this purpose but now I am struggling to implement it. Below is my main.ts file where I had the vuestic override (commented out). Ca ...

The pathway specified is untraceable by the gulp system

Hey there, I've encountered an issue with my project that uses gulp. The gulpfile.js suddenly stopped working without any changes made to it. The output I'm getting is: cmd.exe /c gulp --tasks-simple The system cannot find the path specified. ...

typescript mistakenly overlooked a potential undefined value in indexed records

In my code, I have defined an index-based type X. However, when using a non-existing key, TypeScript does not accurately infer the result type as ValueType | undefined. Is there a solution to correct this issue? type ValueType = { foobar:string; } t ...

Sharing data from a Provider to a function in React can be done through various methods

After developing an NPM library that contains various utility functions, including one for calling endpoints, I encountered a roadblock when trying to set the Axios.create instance globally. Initially, my idea was to create a Provider and establish a cont ...

Is it possible to make the 'keyof' property optional?

Illustrate an interface in the following way interface Properties { apple?: string banana?: string cherry?: string date: string } Executing this code works as expected type Sample1 = { [P in keyof Properties]: Properties[P] } const s1: Sample1 ...

Using a split string to destructure an array with a mix of let and const variables

There is a problem with TS: An error occurs stating that 'parsedHours' and 'parsedMinutes' should be declared as constants by using 'const' instead of 'prefer-const'. This issue arises when attempting to destructure ...

The count of bits is not producing the anticipated result

Attempting to tackle the challenge of Counting Bits using JavaScript, which involves determining the number of set bits for all numbers from 0 to N, storing them in an array, and returning the result Let me provide an explanation Input: n = 5 ...

Storing information retrieved from the API for use in different modules

Trying to extract data from a WEB API service using Angular 8 has been quite challenging for me. A service I created makes the API call: return this.http.get<UserSession>(uri) .pipe(map((json: UserSession) => this.EntryFormAdapter(json))); Th ...

Experimenting with Date Object in Jest using Typescript and i18next

I have included a localization library and within my component, there is a date object defined like this: getDate = () => { const { t } = this.props; return new Date().toLocaleString(t('locale.name'), { weekday: "long", ...