porsager/postgres

What would be the right type to pass an object?

Open

#625 aperta il 29 giu 2023

Vedi su GitHub
 (4 commenti) (0 reazioni) (0 assegnatari)JavaScript (230 fork)batch import
Typescripthelp wanted

Metriche repository

Star
 (6221 star)
Metriche merge PR
 (Nessuna PR mergiata in 30 g)

Descrizione

Hello,

in my table "account" the column "contact" is of the type jsonb. Using the following interface, I get an TS Error:

error: TS2769 [ERROR]: No overload matches this call. Overload 1 of 2, '(first: TemplateStringsArray, ...rest: never): PendingQuery<Row[]>', gave the following error. Argument of type 'string' is not assignable to parameter of type 'never'. Overload 2 of 2, '(template: TemplateStringsArray, ...parameters: readonly ParameterOrFragment[]): PendingQuery<Row[]>', gave the following error. Argument of type 'object' is not assignable to parameter of type 'ParameterOrFragment'. return await sql`

I have two questions:

  1. Is it correct to pass an object like this for jsonb?
  2. If yes, what could I do to avoid the TS error?

Thank you very much!

interface AccountData {
  owner: string;
  email: string;
  contact: object;
  password: string;
}

async function insertAccount(
  { owner, email, contact, password }: AccountData,
) {
  return await sql`
    INSERT INTO public.account (owner, email, contact, hashed_password)
    VALUES (${owner}, ${email}, ${contact}, crypt(${password}, gen_salt('md5')))
  `;
}

const dataJane = {
  owner: "Jane Doe",
  email: "janedoe@example.com",
  contact: { "phone": "12345" },
  password: "password123",
};

await insertAccount(dataJane);

Guida contributor