简体   繁体   中英

Typescript define type with function test

I am trying to create types that allow me to only search for specific things.

Lets assume I have this model and data:

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
    }
}

Using mongodb, I can query the root properties:

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

So I created this type to catch errors for things not in my model:

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

Mongodb also allows you to search inside an object such as this:

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

As you can see, now that I am using the previous type, MongoManagerFilter , I get an error that 'party.invites' does not exist in UserModel .

So what I would like to do is run a function like so:

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;
        }
    }
}

And then add another type to do this:

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

Unfortunately, it won't let me run the isDotStringRegExp function in this type.

How do I achieve this?

You cannot call a function with a type. So the function call isDotStringRegExp(T, key) is not possible since both T and key are types.

If you want type-safe access with dot-notation, take a look at this question: https://stackoverflow.com/a/68412497/10857778

If you are looking on how to do this with Mongo, look at my other thread, specifically the playground code.

Typescript Conditional Types Not Figuring Out Type

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM