简体   繁体   English

检查对象是否符合打字稿中的定义

[英]Check if object complies with definition in typescript

I've a data structure like this 我有这样的数据结构

"properties": {
    "email": {
        "type": "string",
        "validations": ["required", "email"]
    },
    "address": {
        "street": {
            "type": "string",
            "validations": ["required"]
        },
        "zip": {
            "type": "number",
            "validations": ["required", "min(5)", "max(5)"]
        }
    }
}

Then I iterate on it using Object.entries(...) How can I check if the object is either of the first type or the second one (which is composite)? 然后,我使用Object.entries(...)对其进行迭代。如何检查对象是第一种还是第二种(复合的)?

I could check for property names, but i want some neat solution using typescript ... any ideas? 我可以检查属性名称,但是我想要使用打字稿的整洁解决方案……有什么想法吗?

Runtime checking is not something that Typescript can help you with, Typescript types are pretty much gone at runtime. 运行时检查不是Typescript可以帮助您的,Typescript类型在运行时几乎消失了。 What Typescript can help you with is compile time checking. Typescript可以帮助您的是编译时间检查。 A custom type guard would be helpful to help you check and then have the variable typed correctly: 自定义类型防护将有助于您检查然后正确键入变量:

type Validation = { type: string, validations: string[] }
type ValidationContainer = { [name: string] : Validation | ValidationContainer };

// Type guard
function isValidation (v: Validation | ValidationContainer) : v is Validation {
    let vv = v as Validation;
    return  typeof vv.type === "string" && vv.validations instanceof Array;
}

function processTree(v:ValidationContainer, parent?:string) {
    for(let [key, value] of Object.entries(v)) {
        // value is  Validation | ValidationContainer
        if(isValidation(value)) {
            // value is Validation here after type guard
            console.log(value.type)
            console.log(value.validations)
        }else{
            // value is Validation here after type guard
            processTree(value, key)
        }
    }
}

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

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