Javascript 如何检查';键';正确填充了';已知';JSON文件中的值
我试图检查一个特定的Javascript 如何检查';键';正确填充了';已知';JSON文件中的值,javascript,json,typescript,user-defined-functions,key-value,Javascript,Json,Typescript,User Defined Functions,Key Value,我试图检查一个特定的键是否只分配了一组值。这些值在Typescript中以enum的形式列出 请注意,我确实希望像下面解释的那样直接检查值,但希望检查枚举类型 我需要检查json文件中只使用了已知区域 export type Regions = Na | Emea | Apac; export interface Na { NA: "na"; } export interface Emea { EMEA: "emea"; } export interface Apac {
键
是否只分配了一组值
。这些值在Typescript中以enum
的形式列出
请注意,我确实希望像下面解释的那样直接检查值
,但希望检查枚举
类型
我需要检查json
文件中只使用了已知区域
export type Regions = Na | Emea | Apac;
export interface Na {
NA: "na";
}
export interface Emea {
EMEA: "emea";
}
export interface Apac {
APAC: "apac";
}
我需要编写一个类似于下面的函数,该函数只检查键区域的已知值
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)
}
如果我理解正确,您希望验证一些JSON数据,就像验证Typescript一样,并检查其中的值是否与您提供的接口匹配。通常,如果不使用Typescript本身,这是不可能的,幸运的是TS提供了我们可以在自己的程序中使用的。以下是最简单的示例: 让
myjson.ts
(描述您的类型)为:
然后你可以写一些类似的东西:
import * as ts from "typescript";
import * as fs from 'fs';
function compile(fileNames: string[], options: ts.CompilerOptions): string[] {
let program = ts.createProgram(fileNames, options);
let emitResult = program.emit();
return ts
.getPreEmitDiagnostics(program)
.concat(emitResult.diagnostics)
.map(d => ts.flattenDiagnosticMessageText(d.messageText, ' '));
}
function validate(someJson: string): boolean {
let source = `
import MyJson from "./myjson";
let x: MyJson = ${someJson};
`;
fs.writeFileSync('tmp.ts', source, 'UTF-8');
let errors = compile(['tmp.ts', 'myjson.ts'], {});
if (errors.length)
console.log(errors.join('\n'));
return errors.length === 0;
}
///
let goodJson = '{ "names": ["a", "b"], "values": [1,2,3] }';
let badJson = '{ "names": ["a", "b", "x"], "values": "blah" }';
console.log('ok', validate(goodJson));
console.log('ok', validate(badJson));
结果将是
ok true
Type '"x"' is not assignable to type 'Name'.
Type 'string' is not assignable to type 'number[]'.
ok false
我通过以下代码实现了这一点:
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;
}
谢谢@georg的回答。
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;
}