typescript 扩展数组原型

dvl*_*vlt 2 arrays prototype typescript

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

Array.prototype.toUppercase = () => {map(String.toUppercase);}
Run Code Online (Sandbox Code Playgroud)

为什么不工作?

多谢!

Alu*_*dad 7

需要先声明该成员才可以实现

interface Array<T> {
  toUpperCase(this: string[]): string[];
}
Run Code Online (Sandbox Code Playgroud)

实现大致如下所示

if (typeof Array.prototype.toUpperCase !== 'function') {
  Array.prototype.toUpperCase = function () {
    return this.map(c => c.toUpperCase());
  };
}
Run Code Online (Sandbox Code Playgroud)

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

运行示例

我们可以看到,如果我们在错误类型的数组上调用此函数,TypeScript 将引发错误

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

['a,', 'b', 'c'].toUpperCase(); // OK
Run Code Online (Sandbox Code Playgroud)

请注意,如果您位于模块上下文中,则需要将声明部分包装在一个declare global块中。

把它放在一起:

// array-augmentations.ts

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

if (typeof Array.prototype.toUpperCase !== 
'function') {
  Array.prototype.toUpperCase = function () {
    return this.map(c => c.toUpperCase());
  };
}
Run Code Online (Sandbox Code Playgroud)