Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ModelObject with relations #2380

Open
ysshir opened this issue Apr 11, 2023 · 1 comment
Open

ModelObject with relations #2380

ysshir opened this issue Apr 11, 2023 · 1 comment
Labels

Comments

@ysshir
Copy link

ysshir commented Apr 11, 2023

Hi,
I've been trying to update property types of Model with ModelObject when using toJSON() method.
here is my example.

class Group extends Model {
  declare id: number;
  declare name: string;

  static get tableName() {
    return 'Group'
  }
}

class Person extends Model {
  declare id: number;
  declare groupId: Group['id'];
  declare name: string;

  declare group: Group;

  static get tableName() {
    return 'Person'
  }

  static get relationMappings() {
    return {
      group: {
        relation  : Model.BelongsToOneRelation,
        modelClass: Group,
        join      : {
          from: `${this.tableName}.groupId`,
          to  : `${Group.tableName}.id`,
        }
      },
    }
  }
}


(async () => {
  const person = await Person.query()
                             .withGraphFetched('group')
                             .findById(1);

  if (person) {
    person.group.id

    const json = person.toJSON();

    // json.group is not ModelObject<Group>
    // still able to access Model's methods
    json.group.$knex();
  }
})();

I want the json.group to be type of ModelObject<Group> after using the toJSON().

I have tried to create new Type for this, but I couldn't...
I wrote something like this.... but not work... even I couldn't fix type error...

export type ModelObject2<T extends Model> = Overwrite<ModelObject<T>, {
  [K in keyof T]
  : T[K] extends Model
    // TS2344: Type 'Model & T[K]' does not satisfy the constraint 'Model'.
    ? ModelObject2<T[K]>
    : T[K] extends Array<infer M extends Model>
      ? ModelObject2<M>[]
      : T[K]
}[keyof T]>

any help will be appreciated, thanks

@ysshir
Copy link
Author

ysshir commented Nov 21, 2023

I could make it.

type ModelObjectRCSV<T extends Model> = Overwrite<ModelObject<T>, {
  [K in keyof ModelObject<T>]
  : T[K] extends Array<infer M extends Model>
    ? ModelObjectRCSV<M>[]
    : T[K] extends Model
      ? ModelObjectRCSV<T[K]>
      : T[K]
}>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants