Skip to content

feat: BaseClass|null should be castable to SubClass|null #1976

Closed
@trusktr

Description

@trusktr

This type cast is ok in TypeScript:

class Foo {}
class Bar extends Foo {
  n: i32 = 345
}

let a: Foo | null = null
let b = a as Bar | null

TS playground (no error)

AS playground (runtime error)

The error is:

Uncaught (in promise) RuntimeError: memory access out of bounds

Though depending on the program the stack trace can be different so I didn't include that part. Only the error message is the same.


Workaround for the time being:

class Foo {}
class Bar extends Foo {
  n: i32 = 345
}

let a: Foo | null = null
let b: Bar | null = a == null ? null : a as Bar

AS playground (no error)

But is the workaround good? Is there a way to make the result actually Bar | null in memory shape (whatever that may be)?

It seems the workaround will carry the issue up the call stack to end users (f.e. in the case of return Bar | null), meaning end users of an API will also have to apply the workaround anywhere they receive and subsequently use such a value.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions