2

Actually, I am currently thinking of creating an extension method to all the object or reference that are created in my component

I know how to create an extension method in typeScript but I am not able to get what I want to use an interface to get the behavior I wanted.

I tried using the Object in the interface but it won't work

MyExtension Method : extension.model.ts

declare global {
  interface Object {
    thousandsSeperator(): String;
  }
}

Object.prototype.thousandsSeperator = function(): string {
  return Number(this).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
export {};
// this is just a simple extension method

Now, whenever if someone tries to create an object of class or reference of an interface then, they should get the extension method I created.

// Object
Object1 = new MyComponentClass();

// Reference
Object2: MyComponentClass;

this.Object1.thousandsSeperator();

this.Object2.thousandsSeperator();
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110

1 Answers1

1

fooObj in the below example is assigned to Foo object. so all the methods in the object and the inherited properties can be accessed.

But

fooObj1 is just declared as Foo type. ie, we are declaring that the fooObj1 can only have Object of Foo type.

// Add thousandsSeperator in the Object interface.
interface Object {
    thousandsSeperator(): String;
}

// assign the method to the object prototype.
Object.prototype.thousandsSeperator = function(): string {
    // this is the instance of the object and value is the property on it.
    return Number(this.value).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};
// now all the object of the created will get the thousandsSeperator method.
class Foo {
    value: string = '123456';
}
// create an object 
let fooObj: Foo = new Foo();
// here on the fooObj thousandsSeperator method can be accessed.
fooObj.thousandsSeperator();

// undeclared variable.
let fooObj1: Foo 
// this is eqivalent to var fooObj1; 
Punith Mithra
  • 608
  • 5
  • 9
  • it's working for object and what about interface reference – Dexter's Web Lab Sep 28 '18 at 06:34
  • ya, bro, I know that but how to achieve that for an interface? any logic or suggestions will be helpful – Dexter's Web Lab Sep 28 '18 at 06:54
  • I got an error 1. function not found for that I refer StackOverflow https://stackoverflow.com/questions/45437974/typescript-extend-string-interface-runtime-error 2. after this I got a new error Uncaught TypeError: V[a].exec is not a function extension method for which I prefer https://stackoverflow.com/questions/33063382/jquery-error-matchexprtype-exec-is-not-a-function after that, I went to there ans and found out its forbidden to use Object.prototype – Dexter's Web Lab Sep 28 '18 at 07:30
  • From the first link if you see the string 'translated string' is a String Object. So you can execute string related method on that object. eg: 'a,b,c'.split(',') => ['a', 'b', 'c'] – Punith Mithra Sep 28 '18 at 09:02