1

im try to create a global prototype with a custom function.

I need this:

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

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

I try this:

global.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 {};

When I try to use, fail with this error:

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

And in my class say component.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'

1 Answer 1

1

So try to change the code in your file like this:

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;
}

Then you have to insert the interface inside your typings.d.ts, so the compiler knows there is a change in Object.

typings.d.ts

interface Object{
  _state(): Object; 
}

In the end import your global file inside your module.

app.module.ts

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

That should do the trick. I've tried it and the console.log works like a charm.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.