首页 > 解决方案 > Extending Array in TypeScript for specific type

问题描述

I know how to extend array for any type:

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);
  }
}

Source: Extending Array in TypeScript

But is there also a way to extend the array only for a specific type?. Like only for arrays of type User -> Array<User>.

I want to create a extend method, like .toUsersMap() and this method should not be displayed for arrays, which have not the type User.

标签: arraystypescripttypes

解决方案


您可以实现类似的行为:

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

操场


推荐阅读