首页 > 解决方案 > TypeScript 多态返回类型

问题描述

假设我们要实现数据类型层次结构,应该使用什么类型?

interface Collection<T> {
  map(f: (v: T) => T): ???
}

interface Array<T> extends Collection<T> {
  map(f: (v: T) => T): ??? { return new Array<T>() }
}

interface LinkedList<T> extends Collection<T> {
  map(f: (v: T) => T): ??? { return new LinkedList<T>() }
}

多态化this不起作用

interface Collection<T> {
  map(f: (v: T) => T): this
}

interface Array<T> extends Collection<T> {
  map(f: (v: T) => T): this { return new Array<T> }
  // ^ error `Error: type Array<T> is not assignable to type this`
}

标签: typescript

解决方案


如果我理解正确,您正在寻找的是f 有界多态性(“重载this”)。

interface Collection<T> {
  map(this: Collection<T>, f: (v: T) => T): this;
}

的类型this始终用作第一个参数。请注意,我们可以添加更多重载。例如,要将 aCollection<number>转换为 a Collection<string>,我们可以这样做:

interface Collection<T> {
  map(this: Collection<T>, f: (v: T) => T): this;
  map<U>(this: Collection<T>, f: (v: T) => U): Collection<U>;
}

用法:

declare const collection: Collection<number>;

collection.map(x => x.toString())

推荐阅读