Have interface extend string functionality

2019-05-25 02:18发布

I'm using these tools together:

  • TypeScript
  • Gulp
  • Gulp-Inject

I'm trying to do the following:

module My {
    interface IGulpInjectable extends string { // << Problem here!
        [gulp_inject: string] : string;
    }

    export class Cache {
        private items: { [key: string] : IGulpInjectable };

        constructor() {
            this.items = {
                "item1": { gulp_inject: "file1.html" },
                "item2": { gulp_inject: "file2.html" }
            }
        }

        getItem(key: string){
            return this.items[key].trim();
        }
    }
}

What gulp-inject does is replace { gulp_inject: "x.html" } with a string containing the file contents. This is why I want to have IGulpInjectable extend string: so that methods like trim() will be understood by TypeScript.

However, extends string is not valid. Neither is extends String. At least, not with my current constructor code, which I prefer not to change.

How can I tell TypeScript that my interface has all methods a string has?


Footnote, my current workaround:

        getItem(key: string){
            return (<any> this.items[key]).trim();
        }

But that's not quite satisfying.

2条回答
别忘想泡老子
2楼-- · 2019-05-25 02:49

The following code works fine in typescript playground:

interface IGulpInjectable extends String 
{ 
    gulp_inject: string;
}

class Cache 
{
    private items: { [key: string] : IGulpInjectable };


    constructor() 
    {

        let item1 = new String("   123   ");
        item1["gulp_inject"] = "file1.html";

        let item2 = new String("   4556  ");
        item2["gulp_inject"] = "file2.html";

        this.items = {
            "item1": <IGulpInjectable>item1,
            "item2": <IGulpInjectable>item2
        }
    }

    getItem(key: string)
    {
        return this.items[key];
    }
}

let c = new Cache();
let i = c.getItem("item1");
console.log(i.trim()); //output '123'
console.log(i.gulp_inject); //output 'file1.html'

Link: typescript playground

Hope this helps.

查看更多
\"骚年 ilove
3楼-- · 2019-05-25 03:05

Try changing to:

interface String extends String{
    [gulp_inject: string] : string;
}
查看更多
登录 后发表回答