Skip to content

Suggestions for improving type generation for JSON fields and replacing any with unknown #227

@Leo5878

Description

@Leo5878

Hi! I noticed that in the latest sqlx-ts update, it no longer crashes when encountering JSON fields - thank you so much for that improvement.

I have a couple of suggestions related to type generation, and I might even be able to help implement them.

In my Postgres database, I have a JSON column, and sqlx-ts currently generates an interface like this:

export interface IConfigsUserResult {
  config: object | null;
  config_id: string | null;
  id: number;
}

What if instead of object, we used a generic type? This would allow developers to describe the shape of the JSON stored in the database and use it as the return type:

export interface IConfigsUserResult<T = object> {
  config: T | null;
  config_id: string | null;
  id: number;
}

I understand that this approach mixes layers and that sqlx-ts cannot guarantee the JSON structure, but this responsibility could be left to the developer. If they don’t want to provide a specific type, they can simply omit the generic, and object would be used by default.

Replace types any with unknown

My second suggestion is to replace any with unknown. This would enforce stricter typing and encourage developers to properly validate values returned from the database in cases where sqlx-ts cannot infer a precise type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions