Skip to content

Add NullUndefOr #1

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Add NullUndefOr #1

wants to merge 2 commits into from

Conversation

oyvindberg
Copy link
Collaborator

@oyvindberg oyvindberg commented Aug 26, 2019

Add a set of types for working with Javascript types which can be null/undefined.

In particular, we want to use inheritance to enable us to model the following narrowing of optionality in subtypes. This compiles in Typescript under --strictNullChecks:

interface A {
    a: number | null | undefined
}

interface B extends A {
    a: number | null
}

interface C extends A {
    a: number | undefined
}

interface D extends B, C {
    a: number
}

Using the type hierarchy in this PR we can express this in Scala.js like this:

  trait A extends js.Object {
    val a: NullUndefOr[Int] = js.undefined.asInstanceOf[NullUndefOr[Int]] // note 1
  }

  trait B extends A {
    override val a: NullOr[Int]
  }

  trait C extends A {
    override val a: UndefOr[Int] = js.undefined.asInstanceOf[UndefOr[Int]] // note 1
  }

  trait D extends B with C {
    override val a: Required[Int] // note 2
  }
  • Note 1: Requires change in scala.js to accept js.undefined.asInstanceOf[X] on rhs in @ScalaJSDefined traits.
  • Note 2: This won't work very well when producing Ds, it's impossible to tell scalac that a is not implemented anymore. OTOH consuming this structure coming from javascript is straightforward with a safe d.a.get

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

Successfully merging this pull request may close these issues.

1 participant