Search code examples
typescript

How to extend String Prototype and use it next, in Typescript?


I am extending String prototype chain with a new method but when I try to use it it throws me an error: property 'padZero' does not exist on type 'string'. Could anyone solve this for me?

The code is below. You can also see the same error in Typescript Playground.

interface NumberConstructor {
    padZero(length: number);
}
interface StringConstructor {
    padZero(length: number): string;
}
String.padZero = (length: number) => {
    var s = this;
    while (s.length < length) {
      s = '0' + s;
    }
    return s;
};
Number.padZero = function (length) {
    return String(this).padZero(length);
}

Solution

  • If you want to augment the class, and not the instance, augment the constructor:

    declare global {
      interface StringConstructor {
        padZero(s: string, length: number): string;
      }
    }
    
    String.padZero = (s: string, length: number) => {
      while (s.length < length) {
        s = '0' + s;
      }
      return s;
    };
    
    console.log(String.padZero('hi', 5))
    
    export {}
    

    *The empty export on the bottom is required if you declare global in .ts and do not export anything. This forces the file to be a module. *

    If you want the function on the instance (aka prototype),

    declare global {
      interface String {
        padZero(length: number): string;
      }
    }
    
    String.prototype.padZero = function (length: number) {
      let d = String(this)
      while (d.length < length) {
        d = '0' + d;
      }
      return d;
    };
    
    console.log('hi'.padZero(5))
    
    export {}