Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

objection.js - Can't relate model with an extra property in objection due to typescript error

I'm trying to relate two models with an extra property of "url":

if (typeof session.id === "number") {
  const sessionUser = await Session.relatedQuery("users")
    .for(session.id)
    .relate({
      id: 12345, // error here
      url: "test",
    });
}

The error I get from typescript is this:

Argument of type '{ id: number; url: string; }' is not assignable to parameter of type 'string | number | CompositeId | MaybeCompositeId[] | PartialModelObject | PartialModelObject[]'. Object literal may only specify known properties, and 'id' does not exist in type 'CompositeId | MaybeCompositeId[] | PartialModelObject | PartialModelObject[]'.

However, if I try to relate the models without the extra property, it works perfectly:

if (typeof session.id === "number") {
  const sessionUser = await Session.relatedQuery("users")
    .for(session.id)
    .relate(userId); //userId is just a number e.g. 5
}

Here's my Session model. I also have the extra property on my User model too, as a safety net:

export class Session extends Model {
  host_id?: number;
  url?: string;

  static get tableName() {
    return "sessions";
  }

  static relationMappings = {
    users: {
      relation: Model.ManyToManyRelation,
      modelClass: path.join(__dirname, "User"),
      join: {
        from: "sessions.id",
        through: {
          from: "sessions_users.session_id",
          to: "sessions_users.user_id",
          extra: ["url"],
        },
        to: "users.id",
      },
    },
  };
}

Here are the docs for extra properties: https://vincit.github.io/objection.js/recipes/extra-properties.html

Am I missing anything obvious here?

question from:https://stackoverflow.com/questions/65938915/cant-relate-model-with-an-extra-property-in-objection-due-to-typescript-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't think type inference is capable of understanding which model you're referring to here. I suspect the simple approach is going to look like:

.relate({
  id: 12345,
  url: "test",
} as PartialModelObject<User>);

This as an alternative to declaring the object literal ahead of time, like:

const related: PartialModelObject<User> = { id: 12345, url: "test" };

Untested, but that's the general idea.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...