Unable to associate a model with an additional attribute in objection because of a TypeScript issue

I'm attempting to establish a connection between two models while adding an additional property called "url":

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

The typescript error message I'm receiving is:

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, when I attempt to relate the models without the extra property, it runs smoothly:

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

Below is my Session model. I have also added the extra property on my User model as a precaution:

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 resources regarding extra properties:

Is there something obvious that I might be overlooking?

Answer №1

I believe type inference may struggle to determine the specific model you are referencing in this context. It seems that a straightforward approach could be:

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

Instead of pre-defining the object literal, like so:

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

This is just another way of achieving the same goal without declaring the object ahead of time. Though untested, this conveys the general concept.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does the implementation of my interface differ from what is specified in the TypeScript documentation?

Currently delving into the world of TypeScript documentation https://www.typescriptlang.org/docs/handbook/2/classes.html Specifically focusing on the section implements Clauses, an interesting revelation surfaces: A Word of Caution It’s worth noting t ...

Creating an npm library using TypeScript model classes: A step-by-step guide

Currently, I am working on a large-scale web application that consists of multiple modules and repositories. Each module is being developed as an individual Angular project. These Angular projects have some shared UI components, services, and models which ...

Creating autorest client based on various OpenAPI versions

I'm currently exploring options for creating a Typescript client from our .NET API. After researching various tools, I decided to go with Autorest, as it is Node-based and fits my skillset. While I am aware of Swashbuckle, my knowledge leans more towa ...

Using Angular2, assign a value to the session and retrieve a value from the session

I am having trouble getting and setting a session. Here is my code: login_btnClick() { var NTLoginID = ((document.getElementById("NTLoginID") as HTMLInputElement).value); this._homeService.get(Global.BASE_USER_ENDPOINT + '/EmployeeDe ...

Determine whether a response is not received within 8 seconds

One of the methods in my Angular component is responsible for returning data Here is a snippet of that method getRecognitionById() { this.loaderService.show(null, true); forkJoin( this.vendorWebApiService.getRecognitionById(this.executiveCh ...

Unexpected expression after upgrading to TypeScript 3.7.2 was encountered, file expected.ts(1109)

After updating TypeScript from version 3.6.x to 3.7.2, I started using optional chaining in my code. However, I encountered a peculiar error. Error message: Expression expected.ts(1109) This error appeared in both my (vim, VSCode) IDE, even though the ...

Utilize React Hook Form to easily reset the value of an MUI Select component

I created a dropdown menu where users can select from "Item 1", "Item 2", and "Item 3". Additionally, there is a "Reset" button that allows users to clear their selection and make a new one. Below is the code I used: import React from ...

react-hook-form replaces the onChange function causing delays in updating the value

Recently, I created a unique Select component utilizing useState and onChange. I attempted to integrate this custom component with the powerful react-hook-form. Allow me to share the code snippet for the bespoke Select component. const Select = forwardRef ...

Is there a way to adjust the width of a table cell in Material UI using React?

I encountered a problem where I am attempting to adjust the width of a table cell, specifically in Typescript. However, I am only able to choose between medium and small sizes for TableCellProps. Is there a workaround for this issue? I am looking to expand ...

The deployment on Vercel for a Node Express and TypeScript project is experiencing issues with building

After uploading my project with node using express + typescript, I encountered a problem. The app generates a folder called dist for building, but when vercel deployed my app, it didn't run the build command. To resolve this issue, I had to manually b ...

When is the right time to develop a Node.js application using Typescript with dockerization

Currently, I am developing a full stack TypeScript application using Express for the server and React for the client. The folder structure of my project is organized as shown below: . ├──client/ <-- React app ├──server/ <-- Express serve ...

lines stay unbroken in angular

I am encountering an issue when I execute the following code: DetailDisplayer(row) : String { let resultAsString = ""; console.log(row.metadata.questions.length); (row.metadata.questions.length != 0 )?resultAsString += "Questions ...

What is the reason for calling Proxy on nested elements?

Trying to organize Cypress methods into a helper object using getters. The idea is to use it like this: todoApp.todoPage.todoApp.main.rows.row .first().should('have.text', 'Pay electric bill'); todoApp.todoPage.todoApp.main.rows.ro ...

The elements within the NativeScript components are failing to show the data received from the Django API

My Django API is set up to provide a list of movies titles with their corresponding IDs. I've implemented a movie service in TypeScript that retrieves the list of movie titles and IDs using the GET operation. In my NativeScript project, I have two f ...

Is it advisable to utilize TypeScript interfaces for declaration files and React component prop definitions?

Whenever I create structures for object types, my go-to method is to define them in my declaration.d.ts file like this: type TagsObject = { _id: string; tag: string; } type ProjectData = { _createdAt: string; _id: string; _rev: string; _type: ...

What is the process for including an item in an array within Firestore?

Can someone help me with this code snippet I'm working on: await firebase.firestore().doc(`documents/${documentData.id}`).update({ predictionHistory: firebase.firestore.FieldValue.arrayUnion(...[predictions]) }); The predictions variable is an ar ...

What is the best way to add an external .js file to my Angular 2 application?

I'm currently working on a project using Angular 2's TypeScript API along with webpack to develop a web application. However, I've encountered an issue where one of my components needs to utilize functions from an external .js file that is p ...

Issue: "The argument provided must be a specific string, not a string or an array of strings."

Currently, I am tackling a Vue project that incorporates TypeScript and axios for handling API requests. While working on the Reset Password component, the resetPassword function within the auth.ts file appears as follows: resetPassword(password1: string, ...

Include a conditional statement in ng keypress

When a user types a specific value into a text input, I want to display a specific div. This is what my template looks like: <input type="text" id="jobTitle" (click)="autoCompleteClick()" (keypress)="autoCompleteKeypress()" name="autocomplete" place ...

What could be causing Highlight.js to fail to work following a redirect?

After developing a small application to address a specific issue, I encountered a problem while attempting to apply code highlighting using highlight.js. The issue arises when navigating from site1 to site2 or vice versa - the highlight does not take effec ...