Home > other >  TYPESCRIPT: Function lacks ending return statement and return type does not include 'undefined&
TYPESCRIPT: Function lacks ending return statement and return type does not include 'undefined&

Time:03-29

newbie here with some ugly code. I'm still working on method encapsulation. I'm trying to make code that allows me to compare two input strings and return a boolean value of their "anagram" status, with the conditions shown below. I would greatly appreciate if somebody could provide me with a solution or workaround to the "function lacks ending return statement and return type does not include undefined". Any advice is welcome and appreciated. Thanks in advance!

class Example {
  firstWord = prompt();
  secondWord = prompt();
  public isAnAnagram(firstWord: string, secondWord: string): boolean {
    if (firstWord && secondWord !== null) {
      const firstArray = firstWord.split("");
      const secondArray = secondWord.split("");

      // Show how the firstword and secondword have transformed into arrays
      console.log(firstArray, secondArray);

      let arrayPassed = true;
      if (
        firstArray.every((w) => secondArray.includes(w)) &&
        secondArray.every((w) => firstArray.includes(w))
      ) {
        // Show if first word passes anagram test through console
        console.log("Found all letters of "   firstWord   " in "   secondWord);
      } else {
        arrayPassed = false;
        // Show if first word does not pass anagram test through console
        console.log(
          "Did not find all letters of "   firstWord   " in "   secondWord
        );
      }

      return arrayPassed;
    }
  }
}

CodePudding user response:

You start your function by checking this:

 if (firstWord && secondWord !== null) {

The code inside the if returns a boolean, but there's no else block, and no code after the if. So if code doesn't match the if, you'll be implicitly returning undefined. This contradicts what you told typescript the return type would be: boolean.

public isAnAnagram(firstWord: string, secondWord: string): boolean

To fix this, either add an else case and return a boolean:

else {
  return false
}

Or change the return type to allow you to return undefined.

public isAnAnagram(firstWord: string, secondWord: string): boolean | undefined

CodePudding user response:

You could try using try catch before your return.

  • Related