javascript - 如何检查 'key' 是否正确填充了 JSON 文件中的 'known' 值

标签 javascript json typescript user-defined-functions key-value

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

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

Check if key/value is in JSON

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

export type Regions = Na | Emea | Apac;

export interface Na {
    NA: "na";
}

export interface Emea {
    EMEA: "emea";
}

export interface Apac {
    APAC: "apac";
}

我需要编写一个类似于下面的函数,它只检查已知值用于键 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;
}

最佳答案

做这样的事情:

function isValidRegion(candidate: any): candidate is Regions {
      return Object.keys(Regions).some(region => region === candidate)
}

关于javascript - 如何检查 'key' 是否正确填充了 JSON 文件中的 'known' 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57942107/

相关文章:

javascript - 在 IE 中打开的窗口不起作用

json - 什么是 npm WARN enoent ENOENT : while installing "ws" module in node. js

javascript - 是否有正确的方法将对象键名称映射到更可读的表示形式?

c# - System.Text.Json反序列化错误System.MemoryExtensions无法加载System.Runtime.CompilerServices.Unsafe

node.js - 如何在 Gatsby 中使用 React.lazy

typescript - 如何在 Typescript 中使用 EventTarget

javascript - 获取 HTMLDivElement 的 id

javascript - 处理日期选择器日历小部件中的日期值

javascript - PHP 显示隐藏的 Div

使用 Visual Studio 2015 无法在 Angular 2 上编译 Typescript 文件