Delayed Initialization in TypeScript: Understanding Type Annotations
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 totrue
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.