我知道如何为任何类型扩展数组:
declare global {
interface Array<T> {
remove(elem: T): Array<T>;
}
}
if (!Array.prototype.remove) {
Array.prototype.remove = function<T>(this: T[], elem: T): T[] {
return this.filter(e => e !== elem);
}
}
来源:Extending Array in TypeScript
但是否还有一种方法可以仅针对特定类型扩展数组?。仅适用于 User
类型的数组-> Array<User>
.
我想创建一个扩展方法,比如 .toUsersMap()
并且此方法不应显示为类型不是 User
的数组.
最佳答案
您可以实现类似的行为:
type User = {
tag: 'User'
}
interface Array<T> {
toUsersMap: T extends User ? (elem: T) => Array<T> : never
}
declare var user: User;
const arr = [user]
arr.toUsersMap(user) // ok
const another_array = [{ notUser: true }]
another_array.toUsersMap() // This expression is not callable
如果T
参数没有扩展User
,TS将不允许使用toUsersMap
关于arrays - 在 TypeScript 中为特定类型扩展数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68789779/