Empty string, undefined, null, ...
To check for a truthy value:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
To check for a falsy value:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
Empty string (only!)
To check for exactly an empty string, compare for strict equality against "" using the === operator:
if (strValue === "") {
// strValue was empty string
}
To check for not an empty string strictly, use the !== operator:
if (strValue !== "") {
// strValue was not an empty string
}
Answer from Brian Dukes on Stack OverflowEmpty string, undefined, null, ...
To check for a truthy value:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
To check for a falsy value:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
Empty string (only!)
To check for exactly an empty string, compare for strict equality against "" using the === operator:
if (strValue === "") {
// strValue was empty string
}
To check for not an empty string strictly, use the !== operator:
if (strValue !== "") {
// strValue was not an empty string
}
For checking if a variable is falsey or if it has length attribute equal to zero (which for a string, means it is empty), I use:
function isEmpty(str) {
return (!str || str.length === 0 );
}
(Note that strings aren't the only variables with a length attribute, arrays have them as well, for example.)
Alternativaly, you can use the (not so) newly optional chaining and arrow functions to simplify:
const isEmpty = (str) => (!str?.length);
It will check the length, returning undefined in case of a nullish value, without throwing an error. In the case of an empty value, zero is falsy and the result is still valid.
For checking if a variable is falsey or if the string only contains whitespace or is empty, I use:
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
If you want, you can monkey-patch the String prototype like this:
String.prototype.isEmpty = function() {
// This doesn't work the same way as the isEmpty function used
// in the first example, it will return true for strings containing only whitespace
return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());
Note that monkey-patching built-in types are controversial, as it can break code that depends on the existing structure of built-in types, for whatever reason.
Videos
I believe this is as close as you're going to get only using the typing system (rather than having a 'nonEmptyString' class)
type nonEmptyString = never; // Cannot be implicitly cast to
function isNonEmptyString(str: string): str is nonEmptyString {
return str && str.length > 0; // Or any other logic, removing whitespace, etc.
}
Testing it:
let fn = function(a: nonEmptyString) {
}
let someStr = '';
if (isNonEmptyString(someStr)) {
fn(someStr); // Valid
} else {
fn(someStr); // Compile error
}
Unfortunately, you end up with warts since nonEmptyString is never. Which means you need to explicitly cast nonEmptyString back to string.
let fn = function(a: nonEmptyString) {
let len = a.length; // Invalid
let len2 = (<string>a).length; // Valid
let str = a + 'something else'; // Valid (str is now typed as string)
}
One possible resolution is:
type nonEmptyString = string & { __nonEmptyStr: never };
Which alleviates the problem of having to explicitly cast back to a string (all three tests above are valid), but does pollute the type with __nonEmptyStr (which will be undefined if referenced).
You can use this trick in your specific case:
function fn<T extends string>(a: T extends '' ? never : T) {
// But TypeScript won't know here that !!a === true
}
fn(''); // Error
fn('foo'); // No error
Note that this does NOT work when passing a variable that has type string:
const myEmptyString: string = '';
fn(myEmptyString); // Should error, but does not
I would like to create a type where it accepts all string except empty string. So buttonAriaLabel = "I am button" is acceptable, but if empty string is passed in buttonAriaLabel = " ", this will generate type error like "empty string is not assignable to type..." . I tried following technique (s: string): s is Excluse<typeof s, ' '> but it doesn't work at all. What are the techniques available to achieve this?
type NonEmptyString = {
(s: string): s is Exclude<typeof s, ''>;
};
export interface IButton {
// ... other properties
buttonAriaLabel: NonEmptyString;
}
// Desired Result
const button: IButton = {
// ... other properties
buttonAriaLabel: 'Close', // Valid non-empty string
};
const invalidButton: IButton = {
// ... other properties
buttonAriaLabel: '' ", // TypeScript error: Type " " is not assignable to type 'NonEmptyString'.
};