2

我一起使用这些工具:

  • 打字稿
  • 吞咽
  • Gulp-注入

我正在尝试执行以下操作:

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

用包含文件内容的字符串gulp-inject替换。{ gulp_inject: "x.html" }这就是我想要IGulpInjectable扩展的原因string:这样trim()TypeScript 就能理解类似的方法。

但是,extends string无效。也不是extends String。至少,不是我当前的构造函数代码,我不想改变它。

如何告诉 TypeScript 我的界面具有所有方法string


脚注,我目前的解决方法:

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

但这并不是很令人满意。

4

2 回答 2

0

以下代码在打字稿游乐场中运行良好:

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'

链接:打字稿游乐场

希望这可以帮助。

于 2016-03-16T10:53:32.793 回答
-1

尝试更改为:

interface String extends String{
    [gulp_inject: string] : string;
}
于 2016-03-17T17:13:01.287 回答