kriasoft / knex-types

Generate TypeScript definitions (types) from a PostgreSQL database schema.
MIT License
63 stars 21 forks source link

Make nullable types optional #15

Closed danchr closed 2 years ago

danchr commented 2 years ago

This allows not specifying them.

koistya commented 2 years ago

@danchr can you give an use case example for this? I'm checking how knex returns data from the database, it seems to be never returning undefined for nullable fields...

danchr commented 2 years ago

@danchr can you give an use case example for this? I'm checking how knex returns data from the database, it seems to be never returning undefined for nullable fields...

This is for specifying object literals when writing to the database. With strict null checks, you must initialise the optional fields with null values, otherwise the object isn't valid according to the type. As I see it, an optional field seems to correspond better to the meaning of a nullable column, but I'm not sufficiently familiar with TypeScript to know whether that would be an acceptable change and whether it would change semantics otherwise. So, I left the | null in place, and just made the addition.

koistya commented 2 years ago

@danchr you can initialize a partial db record like this:

import { Knex } from 'knex';

const story: Knex.DbRecord<Story> = {
  id: "xxx",
  title: "Example"
};

-- or --

const story: Partial<Story> = {
  id: "xxx",
  title: "Example"
};

Does this solve your use case? Reference → typescriptlang.org/docs/handbook/utility-types.html#partialtype

danchr commented 2 years ago

@danchr you can initialize a partial db record like this: [snip] Does this solve your use case? Reference → typescriptlang.org/docs/handbook/utility-types.html#partialtype

Indeed, it does; thank you!