microsoft / pxt-microbit

A Blocks / JavaScript code editor for the micro:bit built on Microsoft MakeCode
https://makecode.microbit.org
Other
721 stars 593 forks source link

Cast to class or interface #1916

Open FranklinWhale opened 5 years ago

FranklinWhale commented 5 years ago

Describe the bug In PXT 4.4, cast to class or interface is not supported. image In PXT 5.5, no error is displayed on the JavaScript editor but the code does not run. image image

To Reproduce Steps to reproduce the behavior:

  1. Go to https://makecode.microbit.org/beta
  2. Switch to JavaScript
  3. Paste the code below to the editor
    interface Length {
    length: number;
    }
    function showLength(x: Length) {
    basic.showNumber(x.length);
    }
    showLength([]);
    showLength("X");
  4. See error

Expected behavior Either the cast is disallowed with error or it works successfully.

riknoll commented 5 years ago

This is the expected behavior, but we should probably have a better error in the simulator. The error thrown on hardware is 984 (invalid cast).

See https://makecode.com/js/errorcodes

FranklinWhale commented 5 years ago

The issue here is that member access to string, array and object are handled differently in PXT runtime and, when the type is an interface, it is handled as if it is an object and thus passing string and array into the function causes runtime error.

To make the function work at runtime, the showLength function can be written as follows:

function showLength(x: Length) {
    basic.showNumber(typeof x === "string" ? x.length : Array.isArray(x) ? (x as any[]).length : x.length)
}

Perhaps the error message may mention that an explict type assertion may be required.