Skip to content

Optional chaining type narrowing of void #35236

Closed
@sharno

Description

@sharno

TypeScript Version: 3.7.2

Search Terms:
Type narrowing void
Optional Chaining void

Code

type A = { b: string };

// example of how I try to use it:
async (p: Promise<A>) => {
  const a = await p.catch(console.error);
  a?.b; // error Property 'b' does not exist on type 'void | A'.
};

// simplified examples:
(a: A | void) => {
  a?.b; // error Property 'b' does not exist on type 'void | A'.
  a ? a.b : undefined // works
};

(a: A | undefined) => {
  a?.b; // works
};

(a: A | null) => {
  a?.b; // works
};

Expected behavior:
No errors when using optional chaining with a T | void if T contains the fields specified. I guess void could be represented as a value as undefined considering that a function that returns undefined returns type void.

Not sure if this is feasible

Actual behavior:
compilation error

Playground Link: https://www.typescriptlang.org/play/index.html?ssl=10&ssc=22&pln=10&pc=13#code/C4TwDgpgBAglC8UDeUBGAuKBnYAnAlgHYDmUAvgNwBQVAhliIQMZQAUYmACrgPYC2+LBAA8MAHwBKBGORUoUJj0I4otBKoDutfMChgAdE1rAmAC1aLlPADYR9EXL1wTq82gH59qapRqtamHAAPlAAbjz4ACZS8DJIcqqe3glq7qpeUJgAroSREABmRBCRVL5U-oFQITl5hYTFMXEpST7U5QGwVVCEWdbWjbJuLaXUQA

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions