typescriptstrictnullchecks

Typescript Why type guard does not work as expected for array of objects of type null-able union(strictNullChecks enabled)


type Field = {test: {more: number} | null}
let fields: Field[] = [{test: {more: 55}}]

Transpiler throws error regardless of the type guard:

if (fields[0].test) {
  fields[0].test.more = 55 // object is possibly null
} 

Here no error:

function f(field: Field) {
  if (field.test) field.test.more = 15 // no error
}

Solution

  • Type flow does not keep track of array index access, so it will not remember that you checked the 0 index for null. This was considered but apparently not implemented due to performance considerations You can put the value in a local variable and type guards will work as expected on those:

    type Field = {test: {more: number} | null}
    let fields: Field[] = [{test: {more: 55}}]
    let d = fields[0];
    if (d.test) {
        d.test.more = 55 // object is possibly null
    }