Skip to main content
Module

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

Kysely dialect for PostgreSQL using the deno-postgres client.
Latest
method kysely.InsertQueryBuilder.prototype.$narrowType
Re-export
import { kysely } from "https://deno.land/x/kysely_deno_postgres_dialect@v0.27.1/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 values input when using returning or 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>>