Home > Enterprise >  TypeScript: Declare an object then assign variables in certain conditions
TypeScript: Declare an object then assign variables in certain conditions

Time:05-01

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')
}

CodePudding user response:

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}
  • Related