以字符串属性作为类型指示符的 json 对象的 Typescript 定义文件

标签 typescript jsonschema plotly definitelytyped

我正在研究为 Plotly.js 创建 Typescript 定义文件。我查看了 DefinitelyTyped 存储库中的许多示例定义文件。想到的一个问题是数据对象的接口(interface)。 Data 对象是一个 Traces 数组,如 plot-schema 中所示。 .

考虑这个数据对象的例子。

data = [
    {
         type: 'scatter',  
         x: [1, 2, 3],     
         y: [3, 1, 6],     
         marker: {         
             color: 'rgb(16, 32, 77)' 
         }
    },
    {
         type: 'bar',      
         x: [1, 2, 3],     
         y: [3, 1, 6],     
         name: 'bar chart example' 
    }
];

轨迹类型,例如“散点图”和“条形图”,可以具有不同的属性。例如,“饼图”跟踪类型具有“方向”属性。

虽然我想为每种跟踪类型定义单独的接口(interface),并将公共(public)属性分解到更高级别的接口(interface)中,但我看不到这样做的好方法。

我能想到的最直观的方法是这样的……

interface Trace {
    x: Array<any>;
    y: Array<any>;
}

interface BarTrace extends Trace {
   type: 'bar';
   // bar specific members
}

interface ScatterTrace extends Trace {
    type: 'scatter';
    // scatter specific members
}

这不是有效的 typescript 。需要一个类型,而不是字符串“bar”或“scatter”。

是否有人知 Prop 有类似结构的其他库具有 typescript 定义,或者是否有更好的方法来构建此 JSON 结构的 typescript 定义文件?

最佳答案

我认为您最好的选择是照原样进行,但将 type 定义为字符串。类似于以下内容:

interface Trace {
    type: string;
    x: Array; 
    y: Array; 
}

interface BarTrace extends Trace {
   // bar specific members
}

interface ScatterTrace extends Trace {
    // scatter specific members
}

let data: Array<Trace> = [
    {
         type: 'scatter',  
         x: [1, 2, 3],     
         y: [3, 1, 6],     
         marker: {         
             color: 'rgb(16, 32, 77)' 
         }
    },
    {
         type: 'bar',      
         x: [1, 2, 3],     
         y: [3, 1, 6],     
         name: 'bar chart example' 
    }
];

一旦确定type 是“scatter”还是“bar”,就可以按如下方式转换变量。

data.forEach((item) => {
    if (item.type === 'scatter') {
        let trace: ScatterTrace = item;
        // ...
    } else {
        let trace: BarTrace = item;
        // ...
    }
});

关于以字符串属性作为类型指示符的 json 对象的 Typescript 定义文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34362013/

相关文章:

Angular 应用程序大小突然增加

java - 如何使用 Java 使用另一个 JSON 模式验证 JSON 模式结构?

javascript - 如何创建 string 或 null 类型的 JSON Schema 属性

python - 使用plotly.express 的固定比例轴facetrow/facet_col

python - 使用plotly创建条形图

angular - take is not a function : Angular 7 | Observable. take 抛出运行时错误

javascript - typescript promise 拒绝类型

typescript - 带有泛型参数的类的类型

python-3.x - pymongo 是否支持 json 模式验证?

python - 如何在 Plotly 的 plotly 内定位图例