sajad torkamani
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
})

TypeScript playground

Tagged: TypeScript

Leave a comment

Your email address will not be published. Required fields are marked *