2

I encountered the following error when I wrote code using 'Optional Changing'.

type Foo = {
  b?: number
}

const foo:Foo = {}

if (foo?.b) {
  console.log(foo.b / 10)
}
type Foo = {
  b?: number
}

const foo:Foo = {}

const flag = foo?.b

if (flag) {
  // ERROR: Object is possibly 'undefined'
  console.log(foo.b / 10)
}

The first code is no problem.

However, the second code will cause an error.

Why does this error occur?

Also, I would like to know how to avoid the error by writing the second code!

5
  • if(foo?.b) {...} would work, but that's not the way you want it to work, right? Commented Jan 17, 2021 at 8:37
  • flag is just a variable for typescript, it 'forgets' that it is initialized from foo?.b Commented Jan 17, 2021 at 8:41
  • Yes! I'd prefer to use "const flag = foo?.b". Commented Jan 17, 2021 at 8:42
  • @ddd you can use foo.b! / 10 to inform ts that foo.b will be defined at that time Commented Jan 17, 2021 at 8:46
  • @D Pro I understand that type inference is not working in the second way. But is there any way to make it work? Commented Jan 17, 2021 at 8:47

1 Answer 1

3

Typescript does not track related variables as stated in this issue: https://github.com/microsoft/TypeScript/issues/30539. This ticket also has a link to a larger discussion on how control flow analysis works in TypeScript. Put simply, in the if block, the foo.b is not the same as flag.

What you may do here, instead:

type Foo = {
  b?: number
}

const foo:Foo = {}

const flag = foo?.b

if (flag) {
  console.log(flag / 10)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.