Skip to content

! type assertion on never changes the type #35431

Closed
@Skalman

Description

@Skalman

TypeScript Version: 3.8.0-dev.20191128

Search Terms: ! type assertion, never, wrong type

Code

type A = { kind: "abc" } | { kind: "def" };

function f(a: A) {
  switch (a.kind) {
    case "abc":
      return 1;
    case "def":
      return 2;
    default:
      throw new Error("Bad kind: " + a!?.kind);
      // Hover over `a`:             ^
  }
}

Expected behavior:

Hovering gives the type never.

Actual behavior:

Hovering gives the type A.

Playground Link: The TS playground doesn't work for me

Related Issues: typescript-eslint/typescript-eslint#1282


More context: This is a problem for TypeScript ESLint's "no-unnecessary-type-assertion" rule, which relies on the ! operator not changing the type of the underlying expression.
(@bradzacher, please correct me if I'm misrepresenting anything.)

In the following example, hovering the as always gives the same type:

declare const a: { kind: string } | undefined;

console.log(a!?.kind);
console.log(a?.kind);

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions