在 TypeScript 中扩展 Object.prototype
How to Extend Object.prototype in TypeScript
在 TypeScript 中扩展 Object.prototype:
- 创建一个
object.extensions.ts
文件。 - 扩展
Object
接口,添加扩展方法。 import './object.extensions'
像使用之前一样导入扩展方法。
以下是内容object.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
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.
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:
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.
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
界面:
interface Object { constructor: Function; toString(): string; toLocaleString(): string; valueOf(): Object; hasOwnProperty(v: PropertyKey): boolean; isPrototypeOf(v: Object): boolean; propertyIsEnumerable(v: PropertyKey): boolean; }
例如,这里是您将如何覆盖内置toString()
方法。
interface Object { toString(): string; } Object.prototype.toString = function () { return 'hello'; };
这是我们index.ts
文件中的代码。
import './object.extensions'; const obj = { name: 'Tom', age: 30, }; console.log(obj.toString()); // 👉️ "hello"
请注意,覆盖内置方法会造成混淆,通常应避免使用。