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

Arranging an array of integers followed by sorting by the decimal part of each value in a particular sequence using JavaScript

Below is an example of sorting an array: let arr = ['100.12', '100.8', '100.11', '100.9']; When sorted traditionally, the output is: '100.11', '100.12', '100.8', '100.9' Ho ...

Group data by two fields with distinct values in MongoDB

I have developed a Typescript Node.js application and I am looking to organize documents by two fields, "one_id" and "two_id", based on a specific "one_id" value. Below is the data within my collection: { "_id":"5a8b2953007a1922f00124fd", "one_id ...

Unable to utilize combined data types in React properties

In my theme.interface.ts file, I defined the following 2 types: type ThemeSize = | 'px' | '1' | '1/2' | 'full' | 'fit' type ThemeWidthSpecific = 'svw' | 'lvw' | 'dvw&apos ...

The most suitable TypeScript type for a screen being utilized again in react-navigation v5

When it comes to typing screens under react-navigation v5, I usually follow a simple pattern: // Params definition type RouteParamsList = { Screen1: { paramA: number } Screen2: undefined } // Screen1 type Props = StackScreenProps<R ...

I am looking to generate an array with key-value pairs from an object that will be seen in the examination

I have a task that involves configuring a table and creating objects with key-value pairs for each key. type KeyValuePair<T> = {/** ... */}; let userKeyValuePair :KeyValuePair<{id:number,userName:string}>; // => {key:'id',value: ...

How do you go about making a prop optional in Typescript based on a generic type?

In my app, I have a specific type with optional props based on a generic type: type MyCustomType<R extends Record<string, string> | undefined, A extends string[] | undefined> = { record: R, array: A } There is a function that directly uses ...

A guide to mocking Prisma using Jest mock functionality

Utilizing prisma for database interactions and eager to implement jest-mock to simulate the findMany call. https://jestjs.io/docs/jest-object#jestmockedtitem-t-deep--false brands.test.ts import { PrismaService } from "@services/mysql.service"; i ...

When should I schedule the execution of the .spec and .po.ts files in Protractor?

Curious about TypeScript and Protractor: I have a couple of basic helper functions stored in a shared.po.ts file within my Protractor suite. These functions are triggered by the third it() in my .spec file - meaning they are not immediately called upon ru ...

What's the process for deducing the default generic parameter from a function type?

Is there a way to extract the default type parameter of a function in order to make this statement compile successfully? const fails: string = "" as ReturnType<<T = string>() => T>; ...

Troubles with Typescript typings when including an empty object in an array with specific typings

, I am facing a dilemma with displaying houses in a cart. Each house has an image, but since they load asynchronously, I need to show empty cards until the data is fetched. Initially, I added empty objects to the array representing the houses, which worked ...

Tips on optimizing NextJS for proper integration with fetch requests and headers functionality

I'm currently working on a NextJS project and following the official tutorials. The tutorials demonstrate how to retrieve data from an API using an API-Key for authorization. However, I've run into a TypeScript compilation error: TS2769: No ove ...

The utilization of `ngSwitch` in Angular for managing and displaying

I am brand new to Angular and I'm attempting to implement Form Validation within a SwitchCase scenario. In the SwitchCase 0, there is a form that I want to submit while simultaneously transitioning the view to SwitchCase 1. The Form Validation is fun ...

Upgrading to Angular 14 has caused issues with component testing that involves injecting MAT_DIALOG_DATA

After upgrading Angular from 14.1.1 to 14.2.10 and Material from 14.1.1 to 14.2.7, a peculiar issue arose when running tests with the default Karma runner. I am at a loss as to what could have caused this problem, so any advice would be appreciated. The u ...

Guidance on installing only TypeScript dependencies for building from package.json using npm, ensuring a leaner build without unnecessary 150MB of additional dependencies

Is there a way to optimize the dependency installation process for building, minimizing unnecessary packages and reducing the total download size by avoiding 150MB of excess files? This is more of a query rather than an immediate requirement Current depe ...

Angular StrictNullChecks: "Error - object may be null"

I am encountering an issue with the 'strictNullChecks' setting in my Angular project. This has resulted in numerous errors across my templates (.html), such as: <input #inputValue type="text" (keyup.ent ...

The typescript error "Cannot read properties of undefined" is encountered while trying to access the 'map' function

I was attempting to follow a guide on creating an app using typescript and react, but I'm encountering an error that says "Cannot read properties of undefined (reading 'map')". I'm not sure why this is happening, can someone please offe ...

Utilizing TypeScript namespaced classes as external modules in Node.js: A step-by-step guide

My current dilemma involves using namespaced TypeScript classes as external modules in Node.js. Many suggest that it simply can't be done and advise against using namespaces altogether. However, our extensive codebase is structured using namespaces, ...

How can a TypeScript function be used to retrieve a string (or JSON object)?

When attempting to retrieve data from a web API using TypeScript and return the JSON object, encountering an error has left me puzzled. Inside my function, I can successfully display the fetched data on the console, but when I try to return it with return ...

Adding animation to rows in ngx-datatable: A Guide

I am looking to stack the rows of my data table (ngx) one after the other in a vertical fashion. I want to incorporate [@datatableAnimation], but I'm unsure where to place it. When adding it to <ngx-datatable [@datatableAnimation]>, it only af ...

Modify data in a table using Dialog Component in Angular Material

I need to implement a Material Dialog feature that allows users to update entries in a table by clicking on the "Change Status" button. Check out this functional snippet: https://stackblitz.com/edit/angular-alu8pa I have successfully retrieved data fr ...