打字稿:函数缺少结束返回语句,返回类型不包含'undefined'



这里的新手有一些丑陋的代码。我仍在研究方法封装。我正在尝试制作允许我比较两个输入字符串并返回其"的布尔值的代码;变位词";状态,条件如下所示。如果有人能为我提供一个解决方案或变通办法,我将不胜感激;函数缺少结束返回语句,并且返回类型不包括未定义的";。欢迎并感谢任何建议。提前感谢!

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;
}
}
}

您可以通过检查以下内容来启动您的功能:

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

if内部的代码返回布尔值,但没有else块,if之后也没有代码。因此,如果代码与if不匹配,您将隐式返回undefined。这与您告诉typescript的返回类型boolean相矛盾。

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

要解决此问题,请添加else大小写并返回布尔值:

else {
return false
}

或者更改返回类型以允许您返回undefined

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

您可以在返回之前尝试使用try-catch。

相关内容

最新更新