typescript - 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`
}
解决方案
如果我理解正确,您正在寻找的是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())
推荐阅读
- c# - (int)NullableInt 和 NullableInt.Value 之间有区别吗?
- javascript - 将 angularjs 转换为纯 js 或如何将单个服务器用于 angular JS 和 Flask
- artifactory - Artifactory 没有为 Debian 存储库生成 InRelease 文件
- sql - XMLELEMENT 属性组
- node.js - 无法在 Angular 中创建新项目
- java - Java 解析字符串以进行双重溢出检查
- javascript - 将用户输入添加到 javascript 数组
- javascript - VBA 脚本到 Google 脚本的转换问题一——一个简单的 if 语句
- c - 为什么 _ARM_FEATURE_CRYPTO 没有定义,尽管有 ARMv8 处理器?
- python - 解析嵌套列表并为每个有效列表返回原始字符串