Skip to content

Add const to exact comparisons - #166

Open
rosettaroberts-impact wants to merge 2 commits into
jawj:masterfrom
TheNumberOne:master
Open

rosettaroberts-impact wants to merge 2 commits into
jawj:masterfrom
TheNumberOne:master

Conversation

@rosettaroberts-impact

Copy link
Copy Markdown
Contributor

This improves postgres enum support by making as const not needed in conditions when creating conditions for columns with enum types.

This typescript feature requires typescript 5.0. This might be problematic because the peer dependency is "typescript": ">=4.1".

This is an example of the problem this PR is trying to fix.

Schema
declare module 'zapatos/schema' {
  export type enum_profile_avail_check_status = 'Avail' | 'Unavail' | 'Waiting';

  export namespace profile_avail_check {
    export type Table = 'profile_avail_check';
    export interface Whereable {
      /**
       * **profile_avail_check.status**
       * - `enum_profile_avail_check_status` in database
       * - `NOT NULL`, default: `'Waiting'::enum_profile_avail_check_status`
       */
      status?:
        | enum_profile_avail_check_status
        | db.Parameter<enum_profile_avail_check_status>
        | db.SQLFragment
        | db.ParentColumn
        | db.SQLFragment<
            any,
            | enum_profile_avail_check_status
            | db.Parameter<enum_profile_avail_check_status>
            | db.SQLFragment
            | db.ParentColumn
          >;
    }
  }
}

Before this change, the following code has a typescript error:

db.select('profile_avail_check', {
  status: db.conditions.ne('Waiting'),
});

The reason it has a typescript error is because the type of db.conditions.ne('Waiting') is inferred to be SQLFragment<boolean | null, string>, which is not a subtype of db.SQLFragment<any, enum_profile_avail_check_status>. A workaround is to instead do

db.select('profile_avail_check', {
  status: db.conditions.ne('Waiting' as const),
});

With the workaround, db.conditions.ne('Waiting') is inferred to be SQLFragment<boolean | null, 'Waiting'> which is a subtype of db.SQLFragment<any, enum_profile_avail_check_status>. However, it can be annoying to remember this workaround.

This PR removes the need for the workaround by telling typescript to infer the narrowest type possible for the parameter.

This improves enum support by allowing making `as const` not needed in conditions when creating conditions for columns with enum types.

This typescript feature requires typescript 5.0.
@jawj

jawj commented Jan 29, 2025

Copy link
Copy Markdown
Owner

I think requiring TS 5 probably requires a new major version, so I'll keep this one on the back-burner for now.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants