Ghislain
Ghislain

Reputation: 41

Typescript: trying to extend the String class... can't grab the reference to the string value in a my method

class MString extends String {
    
    constructor(value: string) {
        super(value)
        console.log(typeof this)//string 
    }

    /**
     * replaces substrings in string, based on the keys and values of the 'translation' object passed in.
     * @param str
     * @param translations
     */
    replaceAll(translations: { [key: string]: string }) {
        console.log(this)//MString {}
        let replacedStr: String = this;
        for (const key of Object.keys(translations)) {
            while (replacedStr.includes(key)) {
                replacedStr = replacedStr.replace(key, translations[key]);
            }
        }
        return replacedStr;
    }
}

In the constructor it logs the type of 'this' as string. But in the replaceAll() it logs as MString {}.

I also get the error as follows:

            while (replacedStr.includes(key)) {
                               ^
TypeError: String.prototype.toString requires that 'this' be a String
    at MString.toString (<anonymous>)
    at MString.includes (<anonymous>)
    at MString.replaceAll (/mnt/d/Dev/bullshit/src/index.ts:24:32)
    at Object.<anonymous> (/mnt/d/Dev/bullshit/src/index.ts:34:17)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Module.m._compile (/mnt/d/Dev/bullshit/node_modules/ts-node/src/index.ts:1043:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Object.require.extensions.<computed> [as .ts] (/mnt/d/Dev/bullshit/node_modules/ts-node/src/index.ts:1046:12)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)

The same implementation works in javascript. I tried casting this as String. No avail. I tried calling super.valueOf(). No avail. I tried bind this to the replaceAll() method. No avail. I tried creating a property to hold the string that the object was initialized. But I wasn't allowed to do that apparently.

Why do I seem to lose the reference to the instance of the string once I'm in the replaceAll() method? Is there a way for me to access the value of the string instance?

SOLVED

Thanks to CertainPerformance. I realized that the problem was that I was compiling to es5 javascript. I should have compiled to es6 instead.

Upvotes: 2

Views: 282

Answers (0)

Related Questions