【问题标题】:flow-type for dynamic dependencies of possible values of 'A' attribute (Array<prop>) on values 'B' ([prop: string]: any)flow-type 用于动态依赖 'A' 属性 (Array<prop>) 的可能值对值 'B' ([prop: string]: any)
【发布时间】:2019-06-24 23:40:54
【问题描述】:

我有下一个类型定义:

type $Schema = {
  type?: 'object' | 'string' | 'number' | 'array',
  properties?: { [key: string]: $Schema },
  additionalProperties?: boolean,
  range?: [number, number],
  required?: Array<string>
}

我想更改它以防止将尚未在 properties 中定义的密钥放入 required。 在下一个例子中,使用xx 应该被标记为错误,因为它在'properties'中定义:

{  
  required: ['id', 'xx'],
  properties: { id: { type: 'string' } }
}

更难的例子:

const testSchema = {
  properties: {
    foo: {
      type: 'object',
      properties: {
        bar: {
          type: 'string'
        }
      },
      required: ['buz']
    }
  },
  required: ['foo']
}

我想让在流兼容的 IDE/编辑器中使用 JSON-Schema 时更难出错。

有可能吗?

【问题讨论】:

    标签: javascript node.js flowtype


    【解决方案1】:

    你可以尝试使用 generic + $Keys<...>,像这样:

    type $Schema<T: {[key: string]: $Schema<*>}> = {
      type?: 'object' | 'string' | 'number' | 'array',
      properties?: T,
      additionalProperties?: boolean,
      range?: [number, number],
      required?: Array<$Keys<T>>
    } 
    

    并检查架构:

    const testSchema: $Schema<*> = {
      properties: {
        foo: {
          type: 'object',
          properties: {
            bar: {
              type: 'string'
            }
          },
          required: ['buz']
        }
      },
      required: ['foo']
    }
    

    回复:https://flow.org/try/#0PTAEAEDMBsHsHcBQiAuBPADgU1AEgMoDGAFlgLYCGAPACoBcoA3gNoDWWaDAzigE4CWAOwDmAXQYES5agCoAfAF85oALxNEoUOmwB+BgHJYAIwBWWQin2gAPqH08BIq7f2CArmSNZezuxV68FGj6ADQaoBi8sNi8KPxYXHqgNGGaFAAm6fxxsIIU0AAKUTFxCUlGsLDQWBSCqaCBIlhJzO6e3iGgbV68ovW8WACObvwD6UkAggFBVLgA0hxctHJyiAqgyIS5PFoJKESklBIH0lTyquqakdHepVwMjOGakJUPT5pamFgGxmYWoe8rsVbvF7pcPhCjP43hDYZ9sAYHEJhPpAR8FGiFPUIQNhqMsOkGMx9EY3AAvfSid4YzRY8K4kZjIn6F6wSlrIA

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 2020-05-31
      • 2021-04-24
      • 2022-07-05
      • 2018-08-24
      • 2017-08-31
      相关资源
      最近更新 更多