[英]Importing JSON into interface with discriminated unions
我在將 json 導入使用區分聯合模式的接口時遇到問題。 我在將導入的 json 分配給 ts 中的類型變量時收到的錯誤消息是type: string
is notassignable to type: "A"
。 我明白它想告訴我什么,使用類型轉換as Card[]
是一個簡單的解決方法。 我寧願知道 id 可以在沒有演員的情況下正確解決這個問題,以便打字稿可以正確檢查導入的 json。
以下是接口:
// cards.tsx
export type CardType = "A" | "B";
export interface BaseCard {
type: CardType;
name: string;
}
export interface ACard extends BaseCard {
type: "A";
foo: string;
}
export interface BCard extends BaseCard {
type: "B";
goo: string;
}
export type Card = ACard | BCard;
這是給出錯誤的代碼:
import { Card } from './cards.tsx';
import Cards from './cards.json';
const cards: Card[] = Cards;
示例 json:
[
{ "type": "A", "name": "AName", "foo": "FOO" },
{ "type": "B", "name": "BName", "goo": "GOO" }
]
我在將導入的 json 分配給 ts 中的類型變量時收到的錯誤消息是 type: string is notassignable to type:"A"。 我明白它想告訴我什么,使用類型轉換為 Card[] 是一個簡單的解決方法。
這是錯誤的等效簡化:
type Card = {
a:"A",
value: number
}
const failJSON = {
a: "A",
value: 123
}
const fail: Card = failJSON; // Error: type string not assingable to type "A"
如果它不是 json,您將在創建時斷言推理:
type Card = {
a:"A",
value: number
}
const passJSON = {
a: "A" as "A", // NOTICE!
value: 123
}
const fail: Card = passJSON; // OK
但由於它是一個 JSON 文件,因此您無法在其中添加斷言。 您唯一的選擇是斷言as Card[]
因為您已經知道了。
TypeScript 推斷string | number | boolean
string | number | boolean
string | number | boolean
等,而不是對象的文字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.