Delayed Initialization in TypeScript: Understanding Type Annotations

Tomas Svojanovsky
3 min read1 day ago

There are scenarios where type inference cannot determine a variable’s type effectively, such as when a variable is declared on one line and initialized later.

The Problem: Declaring and Initializing Separately

When a variable is declared without an initial value, TypeScript assigns it an implicit any type, unless you explicitly add a type annotation. This situation typically arises when declaration and initialization happen on separate lines, as shown below:

const words = ['red', 'green', 'blue'];
let foundWord;

for (let i = 0; i < words.length; i++) {
if (words[i] === 'green') {
foundWord = true;
}
}

console.log(foundWord);
  • An array of strings, words, is declared and initialized
  • A variable foundWord is declared without an initial value
  • Inside a for loop, foundWord is set to true if the word 'green' is found in the array

The Challenge: Implicit any Type

When you hover over foundWord in your TypeScript-enabled editor, you’ll notice a warning indicating that it has an implicit any type.

--

--

Tomas Svojanovsky
Tomas Svojanovsky

Written by Tomas Svojanovsky

I'm a full-stack developer. Programming isn't just my job but also my hobby. I like developing seamless user experiences and working on server-side complexities

No responses yet