使用typescript扩展“内置”类(例如Array
)时,有没有办法覆盖类方法签名?
例如,如果我想扩展Array<T>
并提供可以给我类型安全的#concat()
方法(即,只允许连接相同类型的数组),那可能吗?
这与我正在尝试的代码类似:
class List<T> extends Array<T> {
public concat(...lists: T[][]): List<T> {
// code here
}
}
这是打字稿输给我编辑的巨大错误:
[ts] Class 'List<T>' incorrectly extends base class 'T[]'.
Types of property 'concat' are incompatible.
Type '(...lists: T[][]) => List<T>' is not assignable to type '{ <U extends T[]>(...items: U[]): T[]; (...items: T[]): T[]; }'.
Type 'List<T>' is not assignable to type 'T[]'.
Types of property 'concat' are incompatible.
Type '(...lists: T[][]) => List<T>' is not assignable to type '{ <U extends T[]>(...items: U[]): T[]; (...items: T[]): T[]; }'.
Types of parameters 'lists' and 'items' are incompatible.
Type 'T' is not assignable to type 'T[]'.
class List<T>
这有什么办法吗?或者我最好只创建一个新的方法名称?