Есть много похожих вопросов, но ни один из них не решает мой запрос.
Вот мой код:
if (commandFn === "/fetch") {
let userFetched: string;
returnText = `${commandFn} used with ${commandArg}`;
admin.database
.ref(`/Users/` + commandArg + "/userdata")
.once("value")
.then((snapshot) => {
userFetched = snapshot.val().userdata;
});
return res.status(200).send({
method: "sendMessage",
chat_id,
text: `${returnText} /n ${userFetched}`,
});
}
Почему говорится, что переменная не назначена? В других функциях, где мне не нужно использовать функцию admin.database, я просто добавил оператор return в блок if.
В моем коде много операторов if-else, которые изменяют текст на вернулся, но та же ошибка. Поэтому я должен добавлять оператор return все время в каждый блок if-else.
Но когда я использую функцию admin.database, я не могу этого сделать. Я снова видел другие подобные ВОПРОСЫ, но они не отвечали на мои.
Это еще один кусок кода, сталкивающийся с той же проблемой:
let numberOfWords: number
for (let index = 1 ; index <= userCommandSlicedLength; index++) {
let lastChar: string = ''
let currentChar: string = ''
currentChar = userCommandSliced.charAt(index)
lastChar = userCommandSliced.charAt(index-1)
if (currentChar === " " && lastChar !== " ") {
numberOfWords = numberOfWords + 1
}
else if (currentChar === " " && lastChar === " ") { // This is a test String.
numberOfWords = numberOfWords + 0
}
}
const finalNumberOfWords: number = numberOfWords
console.log(`Number of words final are = ${finalNumberOfWords}`)
Проблема для второго кода:
src/index.ts:88:25 - error TS2454: Variable 'numberOfWords' is used before being assigned.
88 numberOfWords = numberOfWords + 1
~~~~~~~~~~~~~
src/index.ts:91:24 - error TS2454: Variable 'numberOfWords' is used before being assigned.
91 numberOfWords = numberOfWords + 0
~~~~~~~~~~~~~
src/index.ts:95:40 - error TS2454: Variable 'numberOfWords' is used before being assigned.
95 const finalNumberOfWords: number = numberOfWords