簡體   English   中英

如何將字符串轉換為 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類型的定義確實很復雜,很少有像markencoding.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,您甚至可以明確指定specVisualizationSpec類型,它仍然可以。

您還可以導入子類型並使用它們。 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM