An Unexpected Typescript Error Occurred While Creating an RxCollection With RxDB

I'm new to RxDB and I've come across a strange Typescript error in my Electron project.

Here are the relevant parts of my code:

import RxDB, { RxCollection, RxDatabase } from "rxdb";
RxDB.plugin(require("pouchdb-adapter-idb"));

const heroSchema = {
  title: 'hero schema',
  description: 'describes a simple hero',
  version: 0,
  type: 'object',
  properties: {
    name: {
      type: 'string',
      primary: true
    },
    color: {
      type: 'string'
    }
  },
  required: ['color']
};

// Inside an async function so await works fine
const db = await RxDB.create({ name: "heroedb", adapter: "idb" });

const devices = await db.collection({
     name: "herocollection",
     schema: heroSchema
});

However, Typescript gives me this error:

Argument of type '{ name: string; schema: { title: string; description: string; version: number; type: string; prop...' is not assignable to parameter of type 'RxCollectionCreator'.
Types of property 'schema' are incompatible.
Type '{ title: string; description: string; version: number; type: string; properties: { name: { type: ...' is not assignable to type 'RxJsonSchema | RxSchema<any>'.
Type '{ title: string; description: string; version: number; type: string; properties: { name: { type: ...' is not assignable to type 'RxSchema<any>'.
Property 'jsonID' is missing in type '{ title: string; description: string; version: number; type: string; properties: { name: { type: ...'

Adding jsonID to the schema raises another error about a missing property. It seems like I've made a mistake somewhere. Any insights would be greatly appreciated.

Answer №1

To access the RxDB source code, simply click on this link. When utilizing the RxSchema.create({...}) function, it generates an instance of the RxSchema class ensuring type compatibility. The interface for collection creator includes the following specifications:

export interface RxCollectionCreator {
    name: string;
    schema: RxJsonSchema | RxSchema;
    pouchSettings?: PouchSettings;
    migrationStrategies?: {
        [key: number]: Function
    };
    autoMigrate?: boolean;
    statics?: {
        [key: string]: Function
    };
    methods?: {
        [key: string]: Function
    };
    attachments?: {
        [key: string]: Function
    };
    options?: any;
}

The schema interface can be either RxJsonSchema or RxSchema, with examples provided in the source code. Your object appears to fit the RxJsonSchema type definition, but there may be a missing literal or TypeScript is flagging an extra that needs attention.

export declare class RxJsonSchema {
    title?: string;
    description?: string;
    version: number;
    type: 'object';
    properties: { [key: string]: RxJsonSchemaTopLevel };
    required?: Array<string>;
    compoundIndexes?: Array<string | Array<string>>;
    disableKeyCompression?: boolean;
    additionalProperties?: true;
    attachments?: {
            encrypted?: boolean
    };
}

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

Callbacks are never fired in SQL Server because of the tedious connection

I have successfully connected to a SQL Server instance hosted in Azure through DBeaver and can browse all the data. After installing tedious with the following commands: npm install tedious npm install @types/tedious This is the exact code I am using: im ...

Having trouble with reactjs and typescript? Getting the error message that says "Type 'string' is not assignable to type 'never'"?

When trying to setState with componentDidMount after an axios request is completed, you may encounter the error message Type 'string' is not assignable to type 'never'. Below is the code snippet: import * as React from 'react&apos ...

What could be the reason behind receiving this error message: Failed to import DatePickerField as it is not exported from /..whatever directory?

I've been working on incorporating Formik fields into my material-ui form, and everything is running smoothly except for the date field. It's been quite a struggle, with various issues popping up along the way. Currently, React is giving me this ...

Cypress Issue: Exceeded 5000ms Waiting for `cy.wait()`...No Network Request Detected

I recently decided to dive into building a React app using Vite, Chakra-UI, and TypeScript, incorporating Cypress for testing. The main objective was to expand my knowledge on these technologies. Interestingly enough, this marks my first experience with Cy ...

Error encountered on login page: The protocol 'http' does not exist (related to HTML, TypeScript, Angular2, and JavaScript)

Screenshot of the issue: Access the complete project here: Link to a Plunker example of a log-in screen: http://plnkr.co/edit/j69yu9cSIQRL2GJZFCd1?p=preview (The username and password for this example are both set as "test") Snippet with the error in ...

Error: Prisma seed - encountering issues with undefined properties (unable to read 'findFirst')

I've encountered a strange issue when using prisma seed in my nextjs full-stack project that I can't seem to figure out. Normally, when running the app with `next dev`, everything works smoothly and the queries are executed without any problems. ...

Utilizing various filters and sorting options on API response within Angular 8

Upon receiving the following API response: [ { "imgPaths":[ "gallery/products/55ccb60cddb4d9bded02accb26827ce4" ], "_id":"5f3e961d65c6d591ba04f3d3", "productName":" ...

The compiler is unable to locate the node_module (Error: "Module name not found")

Error: src/app/app.component.ts:4:12 - error TS2591: Cannot find name 'module'. Do you need to install type definitions for node? Try npm i @types/node and then add node to the types field in your tsconfig. 4 moduleId: module.id, When att ...

TypeORM's one-to-many relationship alters the primary entity once the relationship has been established

When working on my side project, I decided to implement a friend request system using NestJS + TypeORM for the backend. However, I encountered a peculiar issue where every time I tried to associate a Friend entity with a specific user, the target field of ...

Obtaining JSON Data from API using Angular 2 Http and the finance_charts_json_callback() Callback

Having trouble retrieving JSON data from this API: I'm unsure how to access the returned finance_charts_json_callback(). Currently, I am utilizing Angular 2's http.get(): loadData() { return this.http .get(this.url) .map((res) => ...

HashId plugin for Angular

Currently, I'm attempting to integrate into my Angular project built on the latest version. After discovering this definition file: // Type definitions for Hashids.js 1.x // Project: https://github.com/ivanakimov/hashids.node.js // Definitions by: ...

Creating a TypeScript type based on the static values of a class

In my Market class, there is only one parameter: name. class Market { name: string constructor(name: string) { this.name = name } } Next, I have a Markets class that contains a static collection of multiple markets. class Markets { static M1 ...

Retrieve the Typescript data type as a variable

I have the following components: type TestComponentProps = { title: string; } const TestComponent: React.FC<TestComponentProps> = ({ title, }) => { return <div>TestComponent: {title}</div>; }; type TestComponent2Props = { bod ...

The RouteParams encounter a problem because it is unable to resolve all parameters

I'm encountering an issue with the RC3 router. The error message I am receiving is: Can't resolve all parameters for RouteParams: (?). Below is my code: //route.ts import {provideRouter, RouterConfig} from '@angular/router'; import {H ...

The compilation of TypeScript extending DataType can sometimes result in errors

I have written a custom extension in my extensions/date.ts file which adds a method to the Date interface: interface Date { addDays: (days: number) => Date } Date.prototype.addDays = function(days: number): Date { if (!days) return this; let dat ...

What is the best way to exhibit information from a get request within an option tag?

My GET request is fetching data from a REST API, and this is the response I receive: { "listCustomFields": [ { "configurationType": null, "errorDetails": null, "fieldId" ...

Error Message: ElectronJS - Attempted to access the 'join' property of an undefined variable

I am currently working on developing a tray-based application. However, I am encountering an error that reads: Uncaught TypeError: Cannot read property 'join' of undefined Can anyone guide me on how to resolve this issue? This is the content ...

Issue occurred while trying to set the value from an API call response in the componentDidMount lifecycle method

There is a boolean variable disableButton: boolean; that needs to be set based on the response received from this API call: async getDocStatus(policy: string): Promise<boolean> { return await ApiService.getData(this.apiUrl + policy + this.myEndpo ...

Issue encountered while implementing async functionality in AngularFireObject

I'm encountering difficulties with the async feature in AngularFireObject. Is there a solution available? Snippet from HomePage.ts: import { AngularFireObject } from 'angularfire2/database'; export class HomePage { profileData: Angu ...

Obtain the name of a node using its identification number in D3JS

I am currently working on implementing a generalized tooltip feature. This tooltip will display the name and other relevant data of the active node. For example, if node 3 is currently active, the tooltip will show the name and distance (not link distance) ...