简体   繁体   中英

Validate if JSON matches type

I am getting some serialized information into my angular application on form if JSON. 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.

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:

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

Based on answer from @bherbruck I changed EventName from type to 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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