以下代码经常会中断,因为标签、描述、详细信息
的类型错误。
所以我想确保他们得到正确的论据:
标签应该是字符串
。
描述应该是字符串或字符串数组
。
详细信息应为字符串
。
这是我第一次使用 TypeScript,所以我检查了 official interface文档。并包含一个界面:
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在评论中提到的,你union type声明错误,应该用 |
分隔,而不是 ||
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 { ... }; }
到 () => ({ ... })
,这只是编写此类表达式的更方便的方法。
关于javascript - 如何使用 TypeScript 接口(interface)检查这三个值的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59916037/