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?
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;
}