arrays - 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
.
解决方案
您可以实现类似的行为:
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
推荐阅读
- android - Android Studio 创建项目生成带有垃圾字符的colors.xml
- javascript - 这个函数参数来自哪里?
- reactjs - 如何在谷歌地图 API 中移动 infoWindow
- ios - 其他 iOS 应用程序版本号
- javascript - 打开需要打开两次的模态
- python - 如何在flask python中通知用户计算的进度
- vue.js - 在 chrome 开发工具(vuejs)中显示所有对象变量
- javascript - 下拉菜单选项标签内的css线性渐变
- javascript - 如何编码“设置图像大小=点击次数+100”?
- java - 网格中的机器人 - DS