sqlc-dev / sqlc-gen-typescript

364 stars 17 forks source link

feat: Option to use undefined instead of null for optional arguments / nullable columns #33

Open mecab opened 5 months ago

mecab commented 5 months ago

Hi, I find sqlc and sqlc-gen-typescirpt are amazing!

Currently, the null type is used to indicate optional parameters, so the following query

-- name: CreateBook :one
INSERT INTO book (title, description)
VALUES (@title, COALESCE(@description, '':text))
RETURNING *;

generates the following argument type

export interface CreateBookArgs {
    title: string;
    description: string | null;
}
export async function createBook(client: Client, args: CreateBookArgs): Promise<CreateBookRow | null> {

which does not allow us to omit the empty fields so you have to always specify null.

createBook(client, { title: "a book" }); // error

createBook(client, { title: "a book", description: null }); 

I think it would be more convenient if there's an option to use undefined instead.

export interface CreateBookArgs {
    title: string;
    description: string | undefined; // or description?: string
}

With this type, you can write

createBook(client, { title: "a book" });

The option should also be useful for the users who use such request parser that coalesces empty inputs as undefined.

The same applies to the returning type (potentially empty row and potentially empty fields).

For implementation, I find pg handles undefined as null so it is purely a type issue, but I have no idea about other engines for now.