如何将模式属性从 json 模式映射到打字稿接口

时间:2021-01-28 11:00:20

标签: json typescript jsonschema

我正在创建一个对应于 json 模式的打字稿接口。我的 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 模式的正确含义。 有人能告诉我怎么做吗?

如何在我的打字稿界面中编写这个东西?

1 个答案:

答案 0 :(得分:0)

假设 patternProperties 中的 key 是一个动态值,我认为这就是您想要的:

interface Style {
    title: string;
    description: string;
    type: string;
    patternProperties: {
        [key: string]: {
            [key: string]: {
                [key: string]: string,
                // or $ref: string
            }[];
        };
    };
}

TS Playground