Skip to content

Setting a value inside a find() results in a type being incorrectly narrowed #39005

@M-Garrett

Description

@M-Garrett

TypeScript Version:
3.9.2

Code

interface example { 
  num: string
  val: string
}
const examples = [
  { num: '1', val: 'A' }, 
  { num: '2', val: 'B' },
  { num: '3', val: 'C' },
]
let a: example | null = null
examples.find(t => { 
  a = t
  return t.num === '2'
})
// a is { num: '2', val: 'B' } 
// but the next line thinks it is of type null and shows compiler errors
if (a !== null && a.num === '2') {
  alert(a.val)
}

Expected behaviour:
No TS errors.

Actual behaviour:
Once it reaches the if, TS thinks that a must be null, despite it's assignment inside the .find(). After the a !== null, a is assumed to be never and prop access causes errors.

Playground Link:
Playground link

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions