【问题标题】:Validate if JSON matches type验证 JSON 是否匹配类型
【发布时间】:2022-01-16 23:33:03
【问题描述】:

如果是 JSON,我会在表单上的 Angular 应用程序中获取一些序列化信息。我想检查事件属性名称是否是我的预定义字符串之一。

事件名称类型:

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

【问题讨论】:

    标签: json angular typescript


    【解决方案1】:

    根据@bherbruck 的回答,我将 EventName 从类型更改为枚举。 所以我的枚举看起来像

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

    验证是

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

    【讨论】:

      【解决方案2】:

      如果您只想将字符串保存在一个位置,可以将它们放入数组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 类型将是:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-14
        • 1970-01-01
        • 1970-01-01
        • 2021-11-06
        • 2011-02-10
        相关资源
        最近更新 更多