Skip to content

Optional chaining, proper infer in type guard #34974

Closed
@maciejsikora

Description

@maciejsikora

TypeScript Version: 3.7.0

Search Terms: optional chaining

Code

type X = {
  y?: {
    z?: string
  }
}
const x: X = {
  y: {
  }
}
// type guard
function isNotNull<A>(x: A): x is NonNullable<A> {
  return x!== null && x!== undefined;
}
// function which I want to call in the result of the expression
function title(str: string) {
  return str.length > 0 ? 'Dear ' + str : 'Dear nobody';
}

isNotNull(x?.y?.z) ? title(x.y.z) : null // type error - object is possibly undefined

The code fix is by adding additional checks or additional temporary variables:

(x?.y?.z && isNotNull(x.y.z)) ? title(x.y.z) : null
// or
const tmp = x?.y?.z
isNotNull(tmp) ? title(tmp) : null

Expected behavior:
TypeScript is able to infer that optional chaining was used as an argument, what means that typeguard is checking the whole chain.

Actual behavior:
TypeScript needs a code change in order to understand that optional chaining already checked other values from being null | undefined.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions