Scala片段到TypeScript(如何转换抽象类型成员)



我在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)
}
}

现在,我正在尝试将这个东西转换为TypeScript。由于我们没有抽象类型成员功能,我似乎找不到在某个时候不需要类型转换的解决方案。

我目前在TypeScript中拥有的内容(也可在操场上获得(

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>> 

我感兴趣的是我们是否可以避免在这里选角:

return new Cons(this.head, this.tail.with(that) as Append<B, That>)

TypeScript似乎理解该值实际上是Append<B, That>,因为它不允许强制转换为任何不同的值,例如Append<B, B>或类似的值。但因为我们使用abtract class RowSet中的with,所以我们最终得到了Cons<A, RowSet>

我们可以用不同的方式定义RowSet吗?这样TypeScript就可以在没有我们帮助的情况下正确地推断出所有内容?也许有一种不同的转换抽象类型成员的方法(从Scala转换时(?

感谢Oleg Pyzhcov的评论,我能够在没有任何手动类型转换的情况下使其工作。F-bounded多态性被认为是解决这个问题的一种方法,事实证明它确实有助于

解决方案看起来是这样的,不需要类型铸造,一切都如预期所示

abstract class RowSet<T extends RowSet<T>> {
abstract with<That extends RowSet<That>>(that: That): Append<T, That>
}
type Append<This extends RowSet<This>, That extends RowSet<That>> =
This extends Cons<infer A, infer B> ? Cons<A, Append<B, That>> : That;
class Empty extends RowSet<Empty> {
public with<That extends RowSet<That>>(that: That): That {
return that;
}
}
class Cons<A, B extends RowSet<B>> extends RowSet<Cons<A,B>> {
constructor(public readonly head: A, public readonly tail: B) {
super();
}
public with<That extends RowSet<That>>(that: That): Cons<A, Append<B, That>> {
return new Cons(this.head, this.tail.with(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>> 

你可以在游乐场上查看

最新更新