Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cast to class or interface #1916

Open
FranklinWhale opened this issue Mar 12, 2019 · 2 comments
Open

Cast to class or interface #1916

FranklinWhale opened this issue Mar 12, 2019 · 2 comments

Comments

@FranklinWhale
Copy link
Contributor

FranklinWhale commented Mar 12, 2019

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");
  1. See error

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

@riknoll
Copy link
Member

riknoll commented Mar 14, 2019

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
Copy link
Contributor Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants