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

29

我正在研究TypeScript和C#中的代码规范,并且我们已经制定了一个规则,即在C#中使用string.Empty代替""

C#示例:

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

TypeScript:

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

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

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

3个回答

16

如果你真的想这么做,你可以编写代码来实现:

interface StringConstructor { 
    Empty: string;
}

String.Empty = "";

function test(x: string) {

}

test(String.Empty);

正如你所看到的,传递String.Empty和只传递""是没有区别的。


6

有一种类型叫做String,它的定义可以在lib.d.ts中找到(这个库也可能在其他地方被定义)。它提供了String类型的常用成员定义,例如fromCharCode。你可以在一个新的TypeScript文件中使用empty来扩展这种类型。

StringExtensions.ts

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

然后调用它

otherFile.ts

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

1
我非常喜欢你的方法,但是tsc返回错误“node_modules/typescript/lib/lib.es2015.core.d.ts(437,11): error TS2451: Cannot redeclare block-scoped variable 'String'. src/app/extensions/StringExtensions.ts(1,15): error TS2451: Cannot redeclare block-scoped variable 'String'." - Vitalii Vasylenko

4

string.Empty是专用于.NET的(感谢@Servy

除了使用"",没有其他创建空字符串的方法。

确实有其他方法,比如new String()'',但你应该关注new String(),因为它返回的不是一个字符串基元,而是一个不同的String对象,这在比较时是不同的(正如这里所述:https://dev59.com/5mkw5IYBdhLWcg3wXpWb#9946836)。


我只是在寻找在TypeScript中定义空字符串的方法。你应该忘记函数... - Veslav
啊,抱歉我有点困惑。 - Florian K

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接