简体   繁体   English

验证 JSON 是否匹配类型

[英]Validate if JSON matches type

I am getting some serialized information into my angular application on form if JSON.如果 JSON,我会在表格上的 angular 应用程序中获取一些序列化信息。 I would like to check if event property name is one of my preDefined strings.我想检查事件属性名称是否是我的预定义字符串之一。

Event name type:事件名称类型:

EventName =
  'appInfo' |
  'connectivity' |
  'location' |
  'pushNotification' |
  'newVersion';
const foo: EventName = 'appInfo';
const bar: EventName = 'appInfos'; // error
const baz: EventName = JSON.parse('appInfos'); // no error
    
// validation
const nameValid = [
  'appInfo', 
  'connectivity', 
  'location', 
  'pushNotification', 
  'newVersion'
].includes(baz) // works, but I would need to change things here and in type if something changes

If you only want to maintain your strings in one place, you could put them in an array as const , then derive a typeof from the array.如果您只想在一个地方维护您的字符串,您可以将它们as const放入一个数组中,然后从该数组派生一个typeof

const EVENT_NAMES = [
  'appInfo',
  'connectivity',
  'location',
  'pushNotification',
  'newVersion',
] as const;

type EventName = typeof EVENT_NAMES[number];

const foo: EventName = 'appInfo';
const bar: EventName = 'appInfos'; // error
const baz: EventName = JSON.parse('appInfos'); // no error

EVENT_NAMES.includes(baz);

EventName type will be: EventName类型将是:

const EVENT_NAMES: readonly ["appInfo", "connectivity", "location", "pushNotification", "newVersion"]

Based on answer from @bherbruck I changed EventName from type to enum.根据@bherbruck 的回答,我将 EventName 从 type 更改为 enum。 So my enum looks like所以我的枚举看起来像

enum EventName {
  AppInfo = 'appInfo',
  Connectivity = 'connectivity',
  Location = 'location',
  PushNotification = 'pushNotification',
  NewVersion = 'newVersion'
}

and validation is验证是

... && Object.values(EventName).includes(this.name);

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

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