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

Ves*_*lav 10 typescript

我正在研究TypeScript和C#中的代码约定,我们已经计算出一个规则来string.Empty代替""C#.

C#示例:

doAction("");
doAction(string.Empty); // we chose to use this as a convention.
Run Code Online (Sandbox Code Playgroud)

打字稿:

// only way to do it that I know of.
doAction("");
Run Code Online (Sandbox Code Playgroud)

现在我的问题是有没有办法在TypeScript中保持这个规则一致,或者这种语言是否具体?

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

thi*_*ple 6

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

interface StringConstructor { 
    Empty: string;
}

String.Empty = "";

function test(x: string) {

}

test(String.Empty);
Run Code Online (Sandbox Code Playgroud)

正如你所看到的那样,传球String.Empty或者传球都没有区别"".


Igo*_*gor 6

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

字符串扩展.ts

declare const String: StringExtensions;
interface StringExtensions extends StringConstructor {
    empty: '';
}
String.empty = '';
Run Code Online (Sandbox Code Playgroud)

然后调用它

其他文件.ts

doAction(String.Empty); // notice the capital S for String
Run Code Online (Sandbox Code Playgroud)