检查对象是否符合typescript中的定义

时间:2018-02-23 17:17:09

标签: typescript

我有这样的数据结构

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

然后我使用Object.entries(...)迭代它 如何检查对象是第一类还是第二类(复合形)?

我可以检查属性名称,但我想要一些使用打字稿的简洁解决方案...任何想法?

1 个答案:

答案 0 :(得分:0)

运行时检查不是Typescript可以帮助你的东西,Typescript类型在运行时几乎消失了。可以帮助您的Typescript是编译时间检查。自定义类型保护将有助于您检查并正确键入变量:

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