typescript-go icon indicating copy to clipboard operation
typescript-go copied to clipboard

Does not completely narrow type through null coalesce operator in switch

Open jkieboom opened this issue 7 months ago • 0 comments

In the following example regular typescript narrows the type of the value in the switch statement to "never" when having checked all cases exhaustively:

interface ClientSource {
  type: "client";
}

interface ServiceSource {
  type: "service";
}

type Source = ClientSource | ServiceSource;

function isDisplaySource(source: Source | null | undefined): boolean {
  switch (source?.type) {
    case "client":
      return true;
    case "service":
      return false;
    case undefined:
      return false;
    default:
      neverReached(source);
      return false;
  }
}

function neverReached(_v: never): void {}

With tsgo however I get the following error:

src/not-reached-narrow.ts:20:20 - error TS2345: Argument of type 'null | undefined' is not assignable to parameter of type 'never'.
  Type 'undefined' is not assignable to type 'never'.

20       neverReached(source);

jkieboom avatar May 26 '25 21:05 jkieboom