簡體   English   中英

使用 JSON 在 Typescript 中定義多種類型

[英]Defining multiple types in Typescript with JSON

我正在導入一個具有不同類型值的 JSON 文件。 JSON 如下所示:

  "l157Logo": "l157.svg",
  "l157": [],
  "l2Logo": "l2.png",
  "l2": [
    {
      "businessName": "Bricklayers Allied Craftworkers Local 2 NY/VT",
      "website": "www.bac2nyvt.org",
      "phone": "518-456-5477",
      "logo": null
    },
    {
      "businessName": "Bricklayers Allied Craftworkers Local 2 NY/VT Joint Benefit Funds",
      "website": "www.bac2funds.com",
      "phone": "518-456-0259",
      "logo": null
    }
  ]
}

我做了一個看起來像這樣的類型:

type unionsJSONSType = {
  [key: string]: {
    businessName: string;
    website: string;
    phone: string;
    logo: string | null;
  }[] | string;
};

在我對打字稿的有限理解中,我是說該值可以是對象數組或字符串。 這對我來說很有意義,但對編譯器來說不是。

我正在分配這樣的類型:

 const unionsFile: unionsJSONSType = unionsJSONS;
 const unionLogo = unionsFile[`${union}Logo`];

當我嘗試像這樣映射它時:


    {unionsFile[union].length > 0 &&
                unionsFile[union].map((provider, index) => {
                  return <SPBusinesses provider={provider} index={index} />;
                })}

這是我得到的錯誤:

  Property 'map' does not exist on type 'string'```
    

TypeScript 對您定義的內容非常嚴格。 無論是字符串還是數組,您對該類型的使用都不得中斷。 如果它是一個字符串, map將中斷。 請注意,數組和字符串都有正確的length ,TypeScript 什么也沒說。 但是您的聯合定義中只有一部分具有map 因此,您已經告訴 TypeScript 您正在冒編譯錯誤的風險。

通過顯式檢查Array正確處理這種情況。

// proper check for array
{Array.isArray(unionsFile[union]) &&
unionsFile[union].map((provider, index) => {
    return <SPBusinesses provider={provider} index={index} />;
})}

讓我們看看導致問題的部分:

unionsFile[union].map

unionsFile的類型是unionsJSONSType ,這意味着它是一個對象,其值為數組或字符串。 unionsFile[union]嘗試訪問unionsFile一個字段——即union求值的字段。

根據字段,相應的值可能是“數組”類型,但也可能是“字符串”類型。 由於字符串沒有map屬性,TypeScript 會抱怨——這是正確的,因為您可能試圖在字符串上調用map ,這將在運行時拋出異常。

本質上,您正在創建數組和字符串的聯合類型,然后嘗試訪問僅適用於數組的方法。 簡而言之,它看起來像這樣:

const data = [['arr'], 'str']
const foo: string[] | string = data[0]
foo.map(x => x)

現在 Typescript 知道它是一個數組或一個字符串。 有了這些知識,它不能保證有一個map方法。 可能它是一個字符串,這會在運行時失敗。 因此它抱怨這種類型不存在map方法。


我看到了這個問題的兩種解決方案:

  1. 使用Array.isArray來確保它是一個數組
const data = [['arr'], 'str']
const foo: string[] | string = data[0]
if (Array.isArray(foo))
  foo.map(x => x)
  1. 重寫您的類型定義,使其必須是一個數組

如果您知道 json 中的特定鍵包含數組,則可以在類型中定義它。

暫無
暫無

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

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