2016-10-04 114 views
0

的JavaScript字符串中打字稿2.0.3以下的原型方法:原型字符串以打字稿

interface String { 
    splice(start: number, delCount: number, newSubStr: string): string; 
} 

String.prototype.splice = function(idx: number, rem: number, str: string): string { 
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem)); 
}; 

引发错误:

error TS2339: Property 'splice' does not exist on type 'String'.

尽管我的界面。它似乎在操场上运行良好。我只在该文件上运行tsc,没有选项。为什么这不起作用?

+0

我跑'tsc'('2.0.3'和'1.8.10')上只包含你的代码,并将其档案工作得很好。你确定这是全部吗? –

回答

2

It seems to work fine in the playground.

那是因为你可能在你的文件的import/export。修复:

declare global { 
    interface String { 
     splice(start: number, delCount: number, newSubStr: string): string; 
    } 
} 

String.prototype.splice = function(idx: number, rem: number, str: string): string { 
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem)); 
}; 

更多

这是这里介绍:https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html#modifying-native-types