DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 39: Nullable Strings

Question: Handling Nullable Strings

Write a function where you need to calculate the length of the string if it's present, or return -1 if it's null. TypeScript's strict type checking can make this seemingly simple task a bit tricky.

const str1: string | null = "Hello, TypeScript!";
const str2: string | null = null;

console.log(getStringLength(str1)); // Output: 18
console.log(getStringLength(str2)); // Output: -1
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
dhrn profile image
Dharan Ganesan
function getStringLength(input: string | null): number {
  if (input === null) {
    return -1;
  }
  // Use type assertion to treat input as a string
  return input.length;
}
Enter fullscreen mode Exit fullscreen mode