2017-03-08 151 views
3

我正在研究TypeScript和C#中的代碼約定,並且我們已經計算出在C#中使用string.Empty而不是""的規則。是否可以在TypeScript中定義string.Empty?

C#示例:

doAction(""); 
doAction(string.Empty); // we chose to use this as a convention. 

打字稿:

// only way to do it that I know of. 
doAction(""); 

現在是我的問題是有沒有辦法讓這個規則一致,打字稿也或者這是特定於語言的?

你們有沒有指針如何在TypeScript中定義一個空字符串?

回答

4

如果你真的想要做這一點,你可以編寫代碼來做到這一點:

interface StringConstructor { 
    Empty: string; 
} 

String.Empty = ""; 

function test(x: string) { 

} 

test(String.Empty); 

但正如你所看到的,將在傳遞的String.Empty或只是沒有什麼區別「」

+0

謝謝,我認爲這是最好的。我們將會使用「」。 – Veslav

1

的String.Empty是專門針對.NET(感謝@Servy

有沒有其他的方法來創建比""

確實有其他的方式,比如new String()''但一個空字符串你應該關心new String(),因爲它返回的不是字符串原語,而是一個字符串對象,它在比較時不同(如此處所述:https://stackoverflow.com/a/9946836/6754146

+0

我只是在尋找各種方法來定義打字稿一個空字符串。你應該忘記功能... – Veslav

+0

啊,對不起,我有點困惑 –

+0

啊謝謝,我現在知道肯定。 – Veslav

2

有一種類型String其中有一個定義發現於lib.d.ts還有其他地方這個庫被定義爲)。它提供String上的類型成員定義,這些定義通常用於fromCharCode。您可以使用empty在新引用的typescript文件中擴展此類型。

StringExtensions.ts

declare const String: StringExtensions; 
interface StringExtensions extends StringConstructor { 
    empty: ''; 
} 
String.empty = ''; 

然後調用它

otherFile.ts

doAction(String.Empty); // notice the capital S for String 
+0

感謝讓@vintern的回答更清晰,但我會給他信用。 ;) – Veslav

+0

我真的很喜歡你的方法,但tsc返回錯誤「node_modules/typescript/lib/lib.es2015.core.d.ts(437,11):錯誤TS2451:無法重新聲明塊範圍變量'String'。 src /app/extensions/StringExtensions.ts(1,15):錯誤TS2451:無法重新聲明塊範圍變量'String'。「 –

相關問題