assemblyscript icon indicating copy to clipboard operation
assemblyscript copied to clipboard

Add Pedantic warnings for explicit downcasting (type refinement)

Open MaxGraey opened this issue 1 year ago • 2 comments

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

MaxGraey avatar Aug 10 '22 13:08 MaxGraey

Hi, I randomly got here from following #2423. Wouldn't Child be a better name than Parent for the extending class :D

georg-getz avatar Aug 12 '22 10:08 georg-getz

@georg-getz good point. Fixed

MaxGraey avatar Aug 12 '22 11:08 MaxGraey