kysely icon indicating copy to clipboard operation
kysely copied to clipboard

[Feature Request]: Implement `$nullable` helper, similar to `$nonNull`.

Open virtuallyunknown opened this issue 1 year ago • 0 comments

Greetings!

I think this can be useful for the following reasons:

  1. I speculate this is probably not too difficult to implement.
  2. A similar helper for $nonNull already exists, "where you know an expression can't be null, but Kysely is unable to infer it.".
  3. I see it having practical application for cases where Kysely infers the type incorrectly (example below)

A quick example where the problem is present, I posted this on the server as well: https://kyse.link/COF71

As proof of concept, I cloned the repository and tweaked aggregate-function-builder.ts to add the following to see if it's gonna work:

export class AggregateFunctionBuilder<DB, TB extends keyof DB, O = unknown> implements AliasableExpression<O> {
  // ...
  $nullable(): AggregateFunctionBuilder<DB, TB, O | null> {
    return new AggregateFunctionBuilder(this.#props)
  }
}

and as far as I can tell, it gets the job done, so that when you use .$nullable(), the value is being inferred as {}[] | null.

The $notNull helper is also present in expression-wrapper.ts, json-path-builder.ts and raw-builder.ts, so I assume a potential new helper would also need to be added there.

Anyway, don't want to make this too long, but let me know if this is a good idea or not, and have a great day.

virtuallyunknown avatar Jul 06 '24 16:07 virtuallyunknown