簡體   English   中英

將導入的 JSON 文件的字符串屬性值映射到具有 TypeScript 的枚舉

[英]Mapping an imported JSON file's string property value to an enum with TypeScript

假設我有以下 JSON:

[
  { "type": "one", "tile": { "x": 0, "y": 0 }},
  { "type": "two", "tile": null }
]

我將它導入到 TypeScript 模塊中:

import dataJson from "data.json";

如果我寫type T = typeof dataJson; T定義為:

type T = ({
  type: string;
  tile: {
    x: number;
    y: number;
  };
} | {
  type: string;
  tile: null;
})[]

但是,我真正想要的是:

enum Type {
  one,
  two
}

interface Entry {
  type: Type,
  tile: {
    x: number,
    y: number
  } | null
}

const data: Entry[] = dataJson;

不幸的是,TypeScript 抱怨這個:

屬性“類型”的類型不兼容。 類型“字符串”不可分配給類型“FeatureType”。 ts(2322)

我知道為什么會發生這種情況,但我似乎找不到解決方法。 有沒有辦法以某種方式強制自動生成typeof dataJson進入Entry

你不喜歡as any明白。 as Entry[]怎么樣?

type Entry = (typeof dataJson)[number] & { type: "one" | "two" }
const data = dataJson as Entry[]

// as oppose to
const data: Entry[] = dataJson
// which still gives you error

TS游樂場

在我看來,您對 TS 中的枚舉並不熟悉,我還包括一些關於該主題的旁注(可選閱讀材料)。

到目前為止,似乎只有以下方法可以做到這一點(感謝@hackape 和@pascalpuetz 讓我到達那里):

import dataJson from "data.json";

enum Type {
  one = "one",
  two = "two"
}

interface Entry {
  type: Type,
  tile: {
    x: number,
    y: number
  } | null
}

// "as any" seems to be the only way to coerce `type: string` to `type: Type`
const data: Entry[] = dataJson as any;

在這種情況下我可以接受, as any JSON 基本上比 TypeScript 的類型要弱得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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