有接口扩展字符串功能 [英] Have interface extend string functionality
问题描述
- TypeScript
- Gulp
- Gulp-Inject
我试图执行以下操作:
module My {
interface IGulpInjectable extends string {//<<问题在这里!
[gulp_inject:string]:string;
}
export class Cache {
private items:{[key:string]:IGulpInjectable};
$ b构造函数(){
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
扩展字符串
:这样像 trim() 将被TypeScript理解。
但是,都不扩展字符串
。至少,不是用我目前的构造函数代码,我不希望改变它。
如何告诉TypeScript我的界面的所有方法都是字符串
有?
脚注,我当前的解决方法:
getItem(key:string){
return(< any> this.items [key])。trim();
}
但这并不令人满意。
interface IGulpInjectable 扩展字符串
{
gulp_inject:string;
}
class Cache
{
private items:{[key:string]:IGulpInjectable};
构造函数()
{
let item1 = new String(123);
item1 [gulp_inject] =file1.html;
let item2 = new String(4556);
item2 [gulp_inject] =file2.html;
$ b $ this.items = {
item1:< IGulpInjectable> item1,
item2:< IGulpInjectable> item2
}
}
getItem(key:string)
{
return this.items [key];
}
}
让c = new Cache();
let i = c.getItem(item1);
console.log(i.trim()); //输出'123'
console.log(i.gulp_inject); //输出'file1.html'
链接:打字游戏场
希望这会有所帮助。
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.
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.
这篇关于有接口扩展字符串功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!