The following code often breaks because label, description, details
have the wrong type.
So I want to make sure they are being fed the right arguments:
label should be string
.
description should be string or array of strings
.
details should be string
.
This is my first time using TypeScript, so I checked the official interface docs. And included an 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()}`
}
})
However, Visual Studio Code is showing me a bunch of errors. So I'm assuming my code isn't even proper TypeScript code.
What's the correct way of doing this?
Update: I tried the suggestion below, but now I have this error:
As @cartant mentioned in the comments, you union type declaration is wrong, it should be separated by |
instead of ||
interface Item {
label: string;
description: string[] | string;
detail: string;
}
It also looks that the map's lambda definition is incorrect. You defined it as (item: Item) => { ... }
which means that input parameter type is Item
. But, I guess that you intended to return that type, so definition should look like: (item): Item => { ... }
quickPick.items = data.map((item): Item => ({
label: item.word,
description: item.tags ? item.tags.join(', ') : 'no tags',
detail: `Relevance: ${item.score.toString()}`
}))
I've also changed () => { return { ... }; }
() => { return { ... }; }
to () => ({ ... })
, it's just a more convenient way to write such expression.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.