如何检查JSON文件中的“键"是否正确填充了“已知"值 [英] How do I check if 'key' is correctly populated with 'known' values in JSON file

查看:114
本文介绍了如何检查JSON文件中的“键"是否正确填充了“已知"值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查特定的key是否仅分配了一组values.此值在Typescript中列为enum.

I am trying to check if a particular key is assigned with only a set of values. This values are listed as an enum in Typescript.

请注意,我这样做是想像下面说明的那样直接检查values,但是想检查enum类型.

Please note, I do that want to check the values directly like it explained below, but would like to check the enum type.

我只需要检查json文件中使用的已知区域.

I need to check only known regions are used in the json file.

export type Regions = Na | Emea | Apac;

export interface Na {
    NA: "na";
}

export interface Emea {
    EMEA: "emea";
}

export interface Apac {
    APAC: "apac";
}

我需要编写类似于下面的函数,该函数仅对键Region的已知值进行检查

I need to write a function similar to below which check of only known values are used for the key Region

function isValidRegion(candidate: any): candidate is Regions {
 // if (candidate is one the type of Regions
 // console.log("Regions valid");
 // else
 // console.log("invalid Regions are used in input JSON");
 result = candidate;
 return result;
}

推荐答案

我是通过以下代码实现的:

I achieved this with the following code:

enum Regions {
NA = "na",
EMEA = "emea",
APAC = "apac"
}

const possibleRegions = [Regions.NA, Regions.EMEA, Regions.APAC];

private isValidRegion(value) 
{
    return value !== null && value.Region !== null && possibleRegions.indexOf(value.Region) > -1;
}

这篇关于如何检查JSON文件中的“键"是否正确填充了“已知"值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆