简体   繁体   English

Typescript 用 function 测试定义类型

[英]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:假设我有这个 model 和数据:

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:使用 mongodb,我可以查询根属性:

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

So I created this type to catch errors for things not in my model:所以我创建了这个类型来捕获不在我的 model 中的错误:

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

Mongodb also allows you to search inside an object such as this: Mongodb 还允许您在 object 中进行搜索,例如:

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 .如您所见,现在我使用的是以前的类型MongoManagerFilter ,我收到一个错误,即UserModel中不存在'party.invites'

So what I would like to do is run a function like so:所以我想做的是像这样运行 function :

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.不幸的是,它不允许我以这种类型运行isDotStringRegExp function。

How do I achieve this?我如何实现这一目标?

You cannot call a function with a type.您不能使用类型调用 function。 So the function call isDotStringRegExp(T, key) is not possible since both T and key are types.所以 function 调用isDotStringRegExp(T, key)是不可能的,因为Tkey都是类型。

If you want type-safe access with dot-notation, take a look at this question: https://stackoverflow.com/a/68412497/10857778如果您想使用点符号进行类型安全访问,请查看以下问题: 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.如果您正在寻找如何使用 Mongo 执行此操作,请查看我的另一个线程,特别是操场代码。

Typescript Conditional Types Not Figuring Out Type Typescript 条件类型未确定类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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