I encountered an error while trying to add an item conditionally to a Map using .filter
, receiving the message
Type 'null' is not assignable to type 'readonly [string, Book]'.(2769)
. This issue seems to arise only when adding items conditionally and using .filter
. How can I successfully construct a Map with conditional items?
type Book = {
author: string,
publishedDate: string,
}
const random = Math.random();
const booksMap = new Map<string, Book>([
['1', {
author: 'Test',
publishedDate: '2024-04-05'
}],
random > 0.5 ? ['1', {
author: 'Test2',
publishedDate: '2023-03-06'
}] : null,
].filter(Boolean))
I have also attempted to filter the tuples outside the Map before passing them into the Map
, but this has not resolved the issue.