Skip to content

Add Pedantic warnings for explicit downcasting (type refinement) #2430

Open
@MaxGraey

Description

@MaxGraey

Downcasting is not cheap and may produce app termination. Much better to use explicit type narrowing + implicit downcasting like:

class Animal {}
class Tiger extends Animal {}
function foo(base: Animal): void {
  if (base instanceof Tiger) {
    let tiger = base; // implicitly infer as base: Tiger
    // use tiger
  }
}

instead of

function foo(base: Animal): void {
   let tiger = <Tiger>base; // may throw "unexpected downcast"
}

Pedantic mode (enabled by --pedantic) should disallow last explicit variant and propose first one.

Depends on #2423 and #2352

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions