簡體   English   中英

如何使用 TypeScript 接口檢查這三個值的類型?

[英]How to check the type of these three values with TypeScript interfaces?

以下代碼經常因為label, description, details類型錯誤而中斷。

所以我想確保他們得到了正確的論點:

標簽應該是string

描述應該是string or array of strings

details 應該是string

這是我第一次使用 TypeScript,所以我查看了官方的接口文檔。 並包含一個接口:

const quickPick = vscode.window.createQuickPick()
const response = await fetch(`https://api.datamuse.com/words?ml=${text.replace(" ", "+")}`)
const data = await response.json() // [{"word": "close", "score": 123, "tags": ["n", "adj"]}

interface Item {
  label: string
  description: string[] || string
  detail: string
}

quickPick.items = data.map((item: Item) => {
  return {
    label: item.word,
    description: item.tags ? item.tags.join(', ') : 'no tags',
    detail: `Relevance: ${item.score.toString()}`
  }
})

但是,Visual Studio Code 向我展示了一堆錯誤。 所以我假設我的代碼甚至不是正確的 TypeScript 代碼。

在此處輸入圖片說明

這樣做的正確方法是什么?

更新:我嘗試了以下建議,但現在出現此錯誤:

在此處輸入圖片說明

正如@cartant 在評論中提到的,你的聯合類型聲明是錯誤的,應該用|分隔而不是||

interface Item {
  label: string;
  description: string[] | string;
  detail: string;
}

看起來地圖的 lambda 定義也不正確。 您將其定義為(item: Item) => { ... }這意味着輸入參數類型為Item 但是,我猜您打算返回該類型,因此定義應如下所示: (item): Item => { ... }

quickPick.items = data.map((item): Item => ({
  label: item.word,
  description: item.tags ? item.tags.join(', ') : 'no tags',
  detail: `Relevance: ${item.score.toString()}`
}))

我也改變了() => { return { ... }; } () => { return { ... }; } to () => ({ ... }) ,這只是一種更方便的方式來編寫這樣的表達式。

暫無
暫無

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

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