I have a small snippet of value level and type level list in Scala
sealed trait RowSet {
type Append[That <: RowSet] <: RowSet
def with[That <: RowSet](that: That): Append[That]
}
object RowSet {
case object Empty extends RowSet {
type Append[That <: RowSet] = That
override def with[That <: RowSet](that: That): Append[That] = that
}
case class Cons[A, B <: RowSet](head: A, tail: B) extends RowSet { self =>
type Append[That <: RowSet] = Cons[A, tail.Append[That]]
override def with[That <: RowSet](that: That): Append[That] = Cons(head, tail ++ that)
}
}
Now, I'm trying to convert this thing to TypeScript. As we don't have the Abstract Type Members feature, I cannot seem to find a solution which doesn't require to type cast at some point.
What I currently have in TypeScript (also available on Playground)
abstract class RowSet {
abstract with<That extends RowSet>(that: That): RowSet
}
type Append<This extends RowSet, That extends RowSet> =
This extends Cons<infer A, infer B> ? Cons<A, Append<B, That>> : That;
class Empty extends RowSet {
public with<That extends RowSet>(that: That): That {
return that;
}
}
class Cons<A, B extends RowSet> extends RowSet {
constructor(public readonly head: A, public readonly tail: B) {
super();
}
public with<That extends RowSet>(that: That): Cons<A, Append<B, That>> {
return new Cons(this.head, this.tail.with(that) as Append<B, That>)
}
}
const x = new Cons(5, new Empty) // Cons<number, Empty>
const y = new Cons("hi", new Empty) // Cons<string, Empty>
const z = x.with(y) // Cons<number, Cons<string, Empty>>
What I'm interested in is if we can avoid casting here:
return new Cons(this.head, this.tail.with(that) as Append<B, That>)
It seems that TypeScript understands that the value is actually Append<B, That> as it doesn't allow to cast to anything different, e.g. Append<B, B> or something similar. But because we use with from abtract class RowSet we end up with Cons<A, RowSet>.
Can we define RowSet differently, so that TypeScript correctly infers everything without our help? Maybe there is a different way of conversion of abstract type members (when converting from Scala)?