1

I have an interface that looks like

export interface Foo {
  data?: Foo;
  bar?: boolean;
}

In some cases, the data is being used as foo.data.bar and in other cases foo.bar. When I use the interface above I'm seeing:

Property 'bar' does not exist on type 'Foo | undefined'

This feels kind of weird, but how can I adjust this so that data could have Foo's types?

1
  • 2
    The problem here is that data can be undefined, so you have to check before access it Commented Mar 25, 2022 at 15:54

1 Answer 1

3

The question mark indicates that data could be either an instance of Foo, or it could be undefined:

data?: Foo;

The error you're seeing is due to this - if data is undefined, there's no bar property to access.

If data will always be populated with an instance of Foo, you can remove the ?, which will resolve this issue:

data: Foo;

Alternatively, you can use optional chaining when accessing bar:

const bar = foo.data?.bar;

Or, you could check if foo.data is defined:

if (foo.data) {
   const bar = foo.data.bar;
}
Sign up to request clarification or add additional context in comments.

1 Comment

"The question mark indicates that data could be either an instance of Foo..." It indicates that a property is optional and is either defined or, like you said, undefined. An instance of Foo would look like let foo = new Foo() where foo is the instance. foo.data can still be undefined.

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.