ts-safeql / safeql

Validate and auto-generate TypeScript types from raw SQL queries in PostgreSQL.
https://safeql.dev
MIT License
1.35k stars 22 forks source link

Interpolated booleans inferred as `boolean | null` (nullability) #268

Open karlhorky opened 2 months ago

karlhorky commented 2 months ago

Describe the bug

TypeScript boolean types in template string interpolation are not correctly inferred as boolean, but instead as boolean | null

To Reproduce Steps to reproduce the behavior:

// 💥 Query has incorrect type annotation.
//  Expected: { has_private_url: boolean; }
//  Actual: { has_private_url: boolean | null; }[]
await sql<{ has_private_url: boolean }[]>`
  SELECT
    ${true as boolean} AS has_private_url
  FROM
    users
`;

Also same problem with no TS type assertion:

// 💥 Query has incorrect type annotation.
//  Expected: { has_private_url: boolean; }
//  Actual: { has_private_url: boolean | null; }[]
await sql<{ has_private_url: boolean }[]>`
  SELECT
    ${true} AS has_private_url
  FROM
    users
`;

Expected behavior

Inference as boolean

Screenshots

--

Desktop (please complete the following information):

Additional context

I was thinking that this may relate to the isColumnNonNullable() function, but since I cannot see anything in the AST related to interpolated values (also not sure what keywords to search for), I'm thinking that maybe the interpolation happens at an earlier step, before the parsing, eg somewhere related to this code:

https://github.com/ts-safeql/safeql/blob/86f5cd6396a11001944d31e8a1ad99ca49497acb/packages/eslint-plugin/src/utils/ts-pg.utils.ts#L61-L98

With a few hints as to how the system works, I would love to open a PR fixing this.

karlhorky commented 2 months ago

Workaround

Wrap the interpolation in coalesce():

await sql<{ has_private_url: boolean }[]>`
  SELECT
    coalesce(${true as boolean}) AS has_private_url
  FROM
    users
`;