'TypeScript: Declare an object then assign variables in certain conditions

I'd like to declare an object, then assign it different values depending on different conditions. Why does this code snippet give the error "Variable 'answer' is used before being assigned."

let answer: {
  diff: number | undefined,
  value: number | undefined,
}


if(answer.diff === undefined) {
  console.log('not defined')
}


Solution 1:[1]

As @VLAZ said, the error is clear, just assign an initial value for the object and it should work now.

let answer: {
  diff: number | undefined,
  value: number | undefined,
} = {diff: undefined, value: undefined}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yago Biermann