是否可以在 TypeScript 中定义 string.Empty?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42674511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:37:10  来源:igfitidea点击:

Is it possible to define string.Empty in TypeScript?

typescript

提问by Veslav

I am researching code conventions in TypeScript and C# and we have figured a rule to use string.Emptyinstead of ""in C#.

我正在研究 TypeScript 和 C# 中的代码约定,我们已经找到了一个规则来string.Empty代替""C# 使用。

C# example:

C# 示例:

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

TypeScript:

打字稿:

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

Now is my question is there a way to keep this rule consistent in TypeScript as well or is this language specific?

现在我的问题是有没有办法在 TypeScript 中保持这个规则的一致性,还是这种语言是特定的?

Do any of you have pointers how to define an empty string in TypeScript?

你们中有人有如何在 TypeScript 中定义空字符串的指针吗?

采纳答案by thitemple

If you really want to do that, you could write code to do this:

如果你真的想这样做,你可以编写代码来做到这一点:

interface StringConstructor { 
    Empty: string;
}

String.Empty = "";

function test(x: string) {

}

test(String.Empty);

As you can see, there will be no difference in passing String.Emptyor just "".

如您所见,通过String.Empty或只是"".

回答by Igor

There is a type Stringwhich has a definition found in lib.d.ts(there are also other places this library is defined). It provides type member definitions on Stringthat are commonly used like fromCharCode. You could extend this type with emptyin a new referenced typescript file.

有一个类型String,它的定义在lib.d.ts还有其他地方定义了这个库)。它提供了String常用的类型成员定义,如fromCharCode. 您可以empty在新的引用打字稿文件中扩展此类型。

StringExtensions.ts

字符串扩展.ts

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

And then to call it

然后调用它

otherFile.ts

其他文件.ts

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

回答by Florian K

string.Empty is Specific to .NET (thanks @Servy)

string.Empty 特定于 .NET(感谢@Servy

There is no other way to create an empty string than ""

没有其他方法可以创建空字符串 ""

Indeed there are other ways, like new String()or ''but you should care about the new String()as it returns not a string primitive, but a String-object which is different when comparing (as stated here: https://stackoverflow.com/a/9946836/6754146)

确实还有其他方法,例如new String()or''但您应该关心 ,new String()因为它返回的不是字符串原语,而是比较时不同的字符串对象(如此处所述:https: //stackoverflow.com/a/9946836/6754146)