adelsz / pgtyped

pgTyped - Typesafe SQL in TypeScript
https://pgtyped.dev
MIT License
2.91k stars 94 forks source link

[Type Generation]: Explicitly Mark Optional TypeScript Properties Using a `?` #573

Open ITenthusiasm opened 6 months ago

ITenthusiasm commented 6 months ago

The Problem

Currently, when generating TS files from SQL queries, the TS types require nullable parameters to be specified. For example

/* 
  @name createAddress
  @param address -> (line1!, line2, city!, state!, zipcode!)
*/
INSERT INTO addresses (line1, line2, city, state, zipcode)
VALUES :address!
RETURNING id;

Generates the following type

/** 'CreateAddress' parameters type */
export interface ICreateAddressParams {
  address: {
    line1: string,
    line2: string | null | void,
    city: string,
    state: number,
    zipcode: string
  };
}

Here, line2 is properly identified as string | undefined | null, but the property itself is not properly marked as optional. Consequently, if I supply an object to createAddress.run that has an optional line2 property, the TypeScript compiler complains even though everything is fine at runtime.

The Solution

I think the simple fix would be to let TypeScript know that nullable parameters/properties are optional. The way to do that would be with a ? So ideally, the following would be generated for optional properties

/** 'CreateAddress' parameters type */
export interface ICreateAddressParams {
  address: {
    // ... Other Properties
    line2?: string | null | void, // notice the `?`
  };
}