gpt4 book ai didi

javascript - 对象原型(prototype)自定义函数 [Angular 7.2 - TS 3.2]

转载 作者:行者123 更新时间:2023-11-30 19:34:05 25 4
gpt4 key购买 nike

我尝试创建一个带有自定义函数的全局原型(prototype)。

我需要这个:

console.log({'active':1, 'profile':1}._state())

{'active':true,'profile':1,'state':'root'}

我试试这个:

全局.ts

declare global {
interface Object {
_state(): Object;
}
}

Object.prototype._state = function (): Object {
if (this.active === 1) {
this.active = true;
}

if (this.profile === 1) {
this.state = 'root';
}

return this;
};

export {};

当我尝试使用时,出现以下错误:

TS2339: Property '_state()' does not exist on type {'active':1, 'profile':1}

在我的课上说组件.ts

import '. /global.ts';

@Injectable()
export class AppState{

constructor(){
console.log({'active':1, 'profile':1}._state());
}
}

TS2345: Argument of type 'AppState' is not assignable to parameter of type 'Object'

最佳答案

因此尝试像这样更改文件中的代码:

global.ts

interface Object{
_state(): Object;
}

Object.prototype._state = function() {
if (this.active === 1) {
this.active = true;
}
if (this.profile === 1) {
this.state = 'root';
}
return this;
}

然后您必须将接口(interface)插入到您的 typings.d.ts 中,以便编译器知道 Object 发生了变化。

typings.d.ts

interface Object{
_state(): Object;
}

最后将您的全局文件导入到您的模块中。

app.module.ts

// make sure the path is right
import './global.ts';

这应该可以解决问题。我试过了,console.log 的效果非常好。

关于javascript - 对象原型(prototype)自定义函数 [Angular 7.2 - TS 3.2],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56130205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com