[英]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
?
到目前為止,似乎只有以下方法可以做到這一點(感謝@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.