How to make TypeScript understand your Array.filter
27 March 2024 (Updated 27 March 2024)
interface Circle {
radius: Number
}
const items: Array<number | Circle> = [2, { radius: 5 }, 5, { radius: 5 }]
// Hover over the variables and you'll see that TypeScript hasn't inferred their types
const nums1 = items.filter(item => {
return typeof item === 'number'
})
const circles1 = items.filter(item => {
return typeof item === 'object' && 'radius' in item
})
// Hover over the variables and you'll see that TypeScript has inferred their types
const nums2 = items.filter((item): item is number => {
return typeof item === 'number'
})
const circles2 = items.filter((item): item is Circle => {
return typeof item === 'object' && 'radius' in item
})
Tagged:
TypeScript
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment