打字稿扩展数组原型 [英] typescript extend Array prototype

查看:52
本文介绍了打字稿扩展数组原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想用一种方法来扩展Array原型,这是我的第一种方法:将sting数组的每个项目都转换为大写:

I just want to extend Array prototype with a method to convert each of the items of a sting array to uppercase, my first approach:

Array.prototype.toUppercase = () => {map(String.toUppercase);}

为什么不起作用?

非常感谢!

推荐答案

您需要先声明成员,然后才能实现

You need to declare the member before you can implement it

interface Array<T> {
  toUpperCase(this: string[]): string[];
}

实现大致如下所示

if (typeof Array.prototype.toUpperCase !== 'function') {
    Array.prototype.toUpperCase = function () {
      return this.map(s => s.toUpperCase());
    };
}

请注意,对现有成员的检查有点草率.仅仅因为它是一个函数并不意味着它具有与我们原先放置在其中的行为相同的行为.通常应避免增强内置原型,但有时很有用.切勿在库中执行此操作,并警告您的代码可能在将来的环境中中断.

Note the check for an existing member is sort of sloppy. Just because it is a function doesn't mean it has the same behavior as what we would otherwise place there. Augmenting builtin prototypes should usually be avoided but sometimes it is useful. Never do this in a library and be warned that your code could break in some future environment.

运行示例

我们可以看到,如果对类型错误的数组调用TypeScript,则会引发错误

We can see that TypeScript will raise an error if we call this on arrays of the wrong type

[1, 2, 3].toUpperCase(); // Error

['a,', 'b', 'c'].toUpperCase(); // OK

请注意,如果您在模块上下文中,则将声明部分包装在 declare global 块中.

Note that if you are in a module context, you would wrap the declaration portion in a declare global block.

这篇关于打字稿扩展数组原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆