Module

x/kysely_postgrs_js_dialect/mod.ts>kysely.InsertQueryBuilder#$narrowType

Kysely dialect for PostgreSQL using the Postgres.js client.
Latest
method kysely.InsertQueryBuilder.prototype.$narrowType
import { kysely } from "https://dotland.deno.dev/x/kysely_postgrs_js_dialect@v0.27.4/mod.ts";
const { InsertQueryBuilder } = kysely;

Narrows (parts of) the output type of the query.

Kysely tries to be as type-safe as possible, but in some cases we have to make compromises for better maintainability and compilation performance. At present, Kysely doesn't narrow the output type of the query based on {@link values} input when using {@link returning} or {@link returningAll}.

This utility method is very useful for these situations, as it removes unncessary runtime assertion/guard code. Its input type is limited to the output type of the query, so you can't add a column that doesn't exist, or change a column's type to something that doesn't exist in its union type.

Examples

Turn this code:

const person = await db.insertInto('person')
  .values({ ...inputPerson, nullable_column: 'hell yeah!' })
  .returningAll()
  .executeTakeFirstOrThrow()

if (nullable_column) {
  functionThatExpectsPersonWithNonNullValue(person)
}

Into this:

const person = await db.insertInto('person')
  .values({ ...inputPerson, nullable_column: 'hell yeah!' })
  .returningAll()
  .$narrowType<{ nullable_column: string }>()
  .executeTakeFirstOrThrow()

functionThatExpectsPersonWithNonNullValue(person)

Returns

InsertQueryBuilder<DB, TB, NarrowPartial<O, T>>