30

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?

0

3 Answers 3

17

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 "".

Sign up to request clarification or add additional context in comments.

Comments

6

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

1 Comment

I really like your approach, but tsc returns error "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'."
5

string.Empty is Specific to .NET (thanks @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)

2 Comments

I was just looking for ways to define an empty string in typescript. You should forget about functions...
Ah, sorry I got kind of confused

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.