Creating a custom type in Typescript using a function for testing purposes

I have been exploring ways to limit my search capabilities to specific criteria.

Let's say I have a model and some data like the following:

interface UserModel {
    _id: string;
    username: string;
    party: UserPartyModel;
}

interface UserPartyModel {
    invites: number;
    rsvps: number;
}

//Test Data
{
    _id: '123',
    username: 'testuser',
    party: {
        invites: 18,
        rsvps: 3
    }
}

When using mongodb, queries can be made based on root properties:

db.users.findOne({_id: '123'});
db.users.findOne({username: 'testuser'});

To handle errors for properties not in the model, I created the type below:

export declare type MongoManagerFilter<T> = {
    [P in keyof T]?: T[P];
};

Mongodb also allows searching within nested objects as demonstrated here:

db.users.findOne({'party.invites': 18});

However, upon utilizing the MongoManagerFilter type, an error is triggered stating that 'party.invites' does not exist in UserModel.

To address this issue, a function like the one below can be employed:

function isDotStringRegExp(obj: Object, dotKey: string): boolean {
    let keyData = dotKey.split('.');
    let objData = obj;

    for (let i = 0; i < keyData.length; i++) {
        let key = keyData[i];
        if (objData.hasOwnProperty(key)) {
            objData = objData[key];
        
            if (i === keyData.length - 1) {
                return true;
            }
        }
        else {
            return false;
        }
    }
}

A new type can then be introduced for this purpose:

export declare type MongoManagerDotStringFilter<T> = {
    [key: string]: (isDotStringRegExp(T, key) ? any : never);
};

Unfortunately, running the isDotStringRegExp function within this type is currently restricted.

Is there a way to achieve this functionality?

Answer №1

Trying to call a function with a type is not allowed. Therefore, calling the function isDotStringRegExp(T, key) is impossible as both T and key are types.

If you're looking for type-safe access using dot notation, refer to this question:

Answer №2

If you're seeking guidance on implementing this using Mongo, check out my other post which includes playground code examples.

Typescript Conditional Types Not Resolving Type

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

Creating encoded objects for a content-type of `application/x-www-form-urlencoded`

Upgrading AngularJS Code to Angular 2+ - Http Issue I am in the process of converting some legacy AngularJS code (specifically Ionic 1) to the latest version of Angular (Ionic 4), and I've encountered a troubling issue. Previously, in every HTTP POS ...

C# MongoDB Driver - Excluding specific fields during deserialization

I need to access the list of Booking collections. Some collections include: Scenario 1 "Countries": [{ "Destinations": [{ "Code": "CHX", "Name": &q ...

Creating a conditional interface based on props in TypeScript: A step-by-step guide

What is the most effective way to implement conditional props in a component that can be either a view or a button based on certain props? Let's take a look at an example called CountdownButtonI: class CountDownButton extends Component<CountdownBut ...

Ways to implement a package designed for non-framework usage in Vue

Alert This may not be the appropriate place to pose such inquiries, but I am in need of some guidance. It's more about seeking direction rather than a definitive answer as this question seems quite open-ended. Overview I've created a package th ...

Guide to accessing a newly opened window from a different domain originating from the current window

Currently working on an Angular project, I am facing a scenario where I have a link on page A that directs users to a different origin page B. The HTML code for the link is shown below: ... <a href="https://another.origin"> PAGE B </a> ... On ...

Adding a Key Value pair to every object within an Array using TypeScript

I have two arrays - one contains dates and the other contains objects. My goal is to include the dates as a key value pair in each object, like this: {"Date": "10-12-18"}. dates: ["10-12-18", "10-13-18", 10-14-18"] data: [ {"name":"One", "age": "4"} ...

What is the reason for the truth value of `type a = {} extends {a?:number}? true:false;`?

Why is type a = {} extends {a?:number}? true:false; evaluated as true, while type b = {a?:number} extends {}? true:false; is also true! It seems like the empty object {} acts as a supertype that can extend other types. This raises some questions about ...

The NUXT project encounters issues when trying to compile

I am currently working on an admin panel using the nuxt + nest stack. I am utilizing a template provided at this link: https://github.com/stephsalou/nuxt-nest-template While in development mode, the project starts up without any issues. However, when I ...

Tips for utilizing a personalized design with the sort-imports add-on in VS Code?

After recently installing the VS Code extension sort-imports, I decided to give a custom style called import-sort-style-module-alias a try. Following what seemed to be the installation instructions (via npm i import-sort-style-module-alias) and updating m ...

Failed to cast value "undefined" to ObjectId in the "_id" path for the model "User"

I've been encountering an issue that I can't seem to resolve despite searching on Stack and Google. My ProfileScreen.js is meant to display a user's profile, but when attempting to view the profile, I receive this error: "Cast to ObjectId fa ...

The click method in the Angular unit test does not seem to be executing successfully

I'm facing a seemingly simple issue where I am unable to confirm that a click handler is being triggered on my component. header.component.ts import { Component, EventEmitter, OnInit, Output } from '@angular/core'; @Component({ selecto ...

Leveraging Java and TypeScript code for specific functionalities within an Ionic 2 Android application

When it comes to creating hybrid apps that support Windows, iOS, and Android simultaneously using web technologies such as Html, CSS, and Js, Ionic is the go-to choice. However, there may be certain features not supported by the Ionic 2 framework. Is it ...

Utilizing MongoDb and Node.js for efficient data input

I am currently facing an issue while trying to input data into a mongodb collection using node.js. I believe I have the necessary access to the collection in question. var collection = db.collection("whatsGoingOnEvents"); if(collection){ console.log("hitt ...

The Observable<T> generic type must be provided with one type argument

I encountered the following 3 errors while working with the Angular 2 (TypeScript) code below. Can you provide suggestions on how to resolve them? import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { NgModule, Com ...

Unexpected date format displayed by the flat picker calendar

The expected date format is "DD-MM-YYYY" but the shown date format in the UI is "YYYY-MM-DD". Click here to view the UI image Initially, before opening the date picker, the date is displayed in the expected format as "DD-MM-YYYY". Upon opening the date p ...

Troubleshooting problems with querying in mongoose and express: A comprehensive guide

As someone who is still relatively new to dynamic routing, I am struggling with implementing it correctly. My goal is to create a function that retrieves the user's purchases from the database and exports it as a CSV file. Everything was working fine ...

What is the best way to individually update elements in an array in Ionic v5?

As a newcomer to Ionic and TypeScript, I would appreciate your kindness in helping me with a problem I am facing. I have an array of objects that get updated when adding an 'exercise', where you can specify the number of sets and reps. The issue ...

What is the best method to completely uninstall Apollo-Angular along with all of its dependencies?

Once I added apollo-angular and @apollo/client to my project, I quickly realized that I no longer needed them. However, simply using "npm uninstall apollo-angular" and "npm uninstall @apollo/client" only removed the main folders but left behind other Apoll ...

Create a function that retrieves the value associated with a specific path within an object

I want to implement a basic utility function that can extract a specific path from an object like the following: interface Human { address: { city: { name: string; } } } const human: Human = { address: { city: { name: "Town"}}}; getIn< ...

Solving commitments through a series of actions

Can someone please explain why when resolving promises in a loop, accessing the loop variable is necessary for it to work correctly? Here's an example where logging occurs 5 times: for (let i = 0; i < 5; i++) { this.getData() .then(() ...