arrays - 在 TypeScript 中为特定类型扩展数组

标签 arrays typescript types

我知道如何为任何类型扩展数组:

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

Playground

关于arrays - 在 TypeScript 中为特定类型扩展数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68789779/

相关文章:

javascript - 在 Angular rxjs 中寻找类似 OrElse 的东西在管道时查找函数

javascript - typescript 和 AngularJS 1.5 : How to handle export class

python - 如何在 Python 中测试对象的类型?

C++ 指向 char 数组

java - java.util.Arrays 中 equals() 的运行时间是多少?

python - 3D numpy 数组到 1D numpy 数组的高效转换

javascript - Typescript:创建一个空的二维数组,然后在不同的位置插入值

typescript - 为什么使用 Array.isArray 时类型推断会丢失?

excel - 无法获取 WorksheetFunction 类的 Vlookup 属性

python - 是否可以直接使用类型提示验证?