如何在 TypeScript 中扩展 Object.prototype

在 TypeScript 中扩展 Object.prototype

How to Extend Object.prototype in TypeScript

在 TypeScript 中扩展 Object.prototype:

  1. 创建一个object.extensions.ts文件。
  2. 扩展Object接口,添加扩展方法。
  3. import './object.extensions'像使用之前一样导入扩展方法。

以下是内容object.extensions.ts

对象.extensions.ts
interface Object { // 👇️ function log - no parameters, returns object log(): Record<string, unknown>; } // 👇️ Don't use arrow function Object.prototype.log = function () { console.log(this); return this as Record<string, unknown>; };


下面是我们如何在原型上
导入和使用新
log方法:Object

索引.ts
import './object.extensions'; const obj = { name: 'Tom', age: 30, }; obj.log();

如果我运行我的index.ts文件,我们可以看到该log方法被成功调用。

对象原型扩展

我们声明了一个新接口Object,它将与原始Object接口合并。

In the interface, we created a log method, which returns an object with
string keys and unknown values.

The method simply logs the object and returns it.

Make sure to use a named function when extending the prototype, and not an arrow function, because arrow functions use the this of the enclosing scope, which is not what you want.

You could use this approach to extend Object.prototype with any method. Here
is an example that implements a merge method that merges 2 objects.

This is the code in the object.extensions.ts file:

object.extensions.ts
interface Object { merge(obj: Record<string, unknown>): Record<string, unknown>; } Object.prototype.merge = function (obj: Record<string, unknown>) { return { ...this, ...obj }; };

And here is the index.ts file, which imports object.extensions and makes use
of the merge method.

index.ts
import './object.extensions'; const obj = { name: 'Tom', age: 30, }; const merged = { country: 'Chile', city: 'Santiago' }.merge(obj); // 👇️ {country: 'Chile', city: 'Santiago', name: 'Tom', age: 30} console.log(merged);

Make sure to specify the correct path when importing the object.extensions.ts
module.

覆盖时Object.prototype,请确保您的方法不会干扰内置方法名称,除非有意覆盖它们(这可能会造成混淆)。

这是原来的Object界面:

索引.ts
interface Object { constructor: Function; toString(): string; toLocaleString(): string; valueOf(): Object; hasOwnProperty(v: PropertyKey): boolean; isPrototypeOf(v: Object): boolean; propertyIsEnumerable(v: PropertyKey): boolean; }

例如,这里是您将如何覆盖内置toString()方法。

对象.extensions.ts
interface Object { toString(): string; } Object.prototype.toString = function () { return 'hello'; };

这是我们index.ts文件中的代码。

索引.ts
import './object.extensions'; const obj = { name: 'Tom', age: 30, }; console.log(obj.toString()); // 👉️ "hello"

请注意,覆盖内置方法会造成混淆,通常应避免使用。