[英]How can I make a complex interface with string indexes with Typescript?
[英]How to cast string to complex and nested interface in Typescript?
我正在将 Javascript 迁移到 Typescript。
我有来自这个 npm pacakage的以下代码。
我想将spec
(作为字符串)转换为VisualizationSpec
类型,以便<VegaLite spec={spec} data={barData} />,
工作。
我试过演员,但它不起作用。 这个接口嵌套复杂,所以我失败了。
如何将字符串转换为 Typescript 中的复杂嵌套接口?
import React from 'react'
import ReactDOM from 'react-dom'
import { VegaLite } from 'react-vega'
const spec = {
width: 400,
height: 200,
mark: 'bar',
encoding: {
x: { field: 'a', type: 'ordinal' },
y: { field: 'b', type: 'quantitative' },
},
data: { name: 'table' }, // note: vega-lite data attribute is a plain object instead of an array
}
const barData = {
table: [
{ a: 'A', b: 28 },
{ a: 'B', b: 55 },
{ a: 'C', b: 43 },
{ a: 'D', b: 91 },
{ a: 'E', b: 81 },
{ a: 'F', b: 53 },
{ a: 'G', b: 19 },
{ a: 'H', b: 87 },
{ a: 'I', b: 52 },
],
}
ReactDOM.render(
<VegaLite spec={spec} data={barData} />,
document.getElementById('bar-container')
);
VisualizationSpec
类型的定义确实很复杂,很少有像mark
、 encoding.x.type
这样的属性需要特定的值。
// vega-lite\src\type.d.ts
export declare type StandardType = 'quantitative' | 'ordinal' | 'temporal' | 'nominal';
// vega-lite\src\mark.ts
export const Mark = {
arc: 'arc',
area: 'area',
bar: 'bar',
image: 'image',
line: 'line',
point: 'point',
rect: 'rect',
rule: 'rule',
text: 'text',
tick: 'tick',
trail: 'trail',
circle: 'circle',
square: 'square',
geoshape: 'geoshape'
} as const;
我复制了你的代码,安装了必要的 npm 包,看到 typescript 抱怨提到的两件事。
有很多解决方法。 对特定属性的 const 断言,整个 object,您甚至可以明确指定spec
是VisualizationSpec
类型,它仍然可以。
您还可以导入子类型并使用它们。 像Mark.bar
'ordinal' as StandardType
const spec = {
width: 400,
height: 200,
mark: "bar" as const,
encoding: {
x: { field: 'a', type: 'ordinal' as const },
y: { field: 'b', type: 'quantitative' as const },
},
data: { name: 'table' },
}
const spec: VisualizationSpec = {
width: 400,
height: 200,
mark: "bar",
encoding: {
x: { field: 'a', type: 'ordinal'},
y: { field: 'b', type: 'quantitative'},
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.