2017-03-08 200 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'。“ –

相关问题