【问题标题】:How can I map a patternProperties from json schema to a typescript interface如何将模式属性从 json 模式映射到打字稿接口
【发布时间】:2021-05-02 06:26:29
【问题描述】:

我正在创建一个对应于 json 模式的 typescript 接口。我的 json 架构中有以下字段:

         "styles": {
            "title": "Style Definitions",
            "description": "Style definition",
            "type": "object",
            "patternProperties": {
                "^.*$": {
                    "oneOf": [
                        { "$ref": "#/definitions/definition1" },
                        { "$ref": "#/definitions/definition2" }
                    ]
                }
            }
         }

我想创建这样的界面:

interface Styles {
    [key: string]: Definition1 | Definition2;
} 

但这是不对的,也没有捕捉到 json 模式的正确含义。 谁能告诉我该怎么做?

如何在我的 typescript 界面中写这个东西?

【问题讨论】:

    标签: json typescript jsonschema


    【解决方案1】:

    我遇到了同样的问题。在我的情况下,我一直希望openapi-typescript 库支持将使用patternProperties 的模式转换为打字稿接口,但目前似乎不支持这一点。 (见the issue我开了)。

    patternProperties 的情况实际上归结为我们是否可以将 Typescript 中的字符串限制为仅匹配给定正则表达式的值。 This is answered here。底线是不直接支持正则表达式限制(尽管有一个开放的proposal 用于包含该功能),因此能够一般将利用patternProperties 的模式转换为等效的Typescript 接口是目前不可能。对于简单的模式,有一个非常接近的东西叫做template literal types

    虽然patternProperties 不是您的主要问题,但您的特定问题。事实上,我认为给定架构:

             "styles": {
                "title": "Style Definitions",
                "description": "Style definition",
                "type": "object",
                "patternProperties": {
                    "^.*$": {
                        ...
                    }
                }
             }
    

    觉得下面这个界面翻译的真好:

    interface Styles {
        [key: string]: ...,
    }
    

    因此,尽管您的问题是标题,但您的 real 问题与将 oneOf 功能从 json 架构实现到打字稿界面有关。 TS 中没有“1 对 1”等价物,答案对于Definition1Definition2 的实际定义非常具体。见this question

    附录:

    我引用的库 openapi-typescript 通过使用 TS 联合 (relevant code) 错误地实现了 oneOf。但正如您所观察到的,这是不正确的。例如,以下是合法的打字稿:

    interface First {
        aString: string;
        aNumber?: number;
    }
    
    interface Second {
        aString: string | boolean;
    }
    
    const tester: First | Second = {
        aString: 'asdgasdf'
    }
    
    console.log(tester);
    

    tester 满足 First AND Second,因此如果这是使用 oneOf 的 jsonschema “等效”,那么 tester 将无法验证。

    【讨论】:

      猜你喜欢
      • 2018-02-06
      • 1970-01-01
      • 2021-08-13
      • 2018-11-09
      • 2021-01-09
      • 2019-07-07
      • 2015-11-29
      • 2019-09-08
      • 1970-01-01
      相关资源
      最近更新 更多