2016-10-04 176 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