【问题标题】:Have interface extend string functionality具有接口扩展字符串功能
【发布时间】:2016-03-16 09:40:04
【问题描述】:

我正在同时使用这些工具:

  • 打字稿
  • 吞咽
  • 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: 以便 TypeScript 能够理解像 trim() 这样的方法。

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

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


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

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

但这并不是很令人满意。

【问题讨论】:

    标签: javascript typescript gulp gulp-inject


    【解决方案1】:

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

    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'
    

    链接:typescript playground

    希望这会有所帮助。

    【讨论】:

    • 但是你必须改变constructor的内部结构很多。如果我想保持原样,您的输入不会 起作用。请参阅 [TypeScript 游乐场](bit.ly/1TNQGwP)。我正在寻找(学习如何)为现有代码创建类型,这就是为什么我不想更改内部结构。
    【解决方案2】:

    尝试更改为:

    interface String extends String{
        [gulp_inject: string] : string;
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-21
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多