Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define string.Empty in TypeScript?

Tags:

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

C# example:

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?

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

like image 759
Veslav Avatar asked Mar 08 '17 14:03

Veslav


People also ask

Is empty string true in TypeScript?

Yes. All false , 0 , empty strings '' and "" , NaN , undefined , and null are always evaluated as false ; everything else is true .

Can a string be null in TypeScript?

TypeScript Null is much like void, i.e. not useful on its own. By default, null is a subtype of all other subtypes which means a user can assign null to any of the data types like string, number, etc.

Can a string be empty?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.


2 Answers

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.Empty or just "".

like image 169
thitemple Avatar answered Sep 29 '22 11:09

thitemple


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

StringExtensions.ts

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

And then to call it

otherFile.ts

doAction(String.Empty); // notice the capital S for String 
like image 35
Igor Avatar answered Sep 29 '22 13:09

Igor