When I try to use type narrowing on a private member, I get a typescript error
You can see an example below.
class Inventory {
private book?: string;
hasBook(): this is { book: string } {
return !!this.book;
}
// Example method
bookLength(): number | undefined {
const hasBook = this.hasBook();
if (hasBook) {
// TypeScript knows that `this.scmAdapter` exists here
return this.book.length;
} else {
return undefined;
}
}
}
The line return this.book.length;
will show a typescript error
Property 'book' does not exist on type 'never'.
The intersection 'this & { book: string; }' was reduced to 'never' because property 'book' exists in multiple constituents and is private in some.
I really want to use type narrowing and avoid using null assertion or optional chaining or other workarounds.
Is there a way to get this to work that I am missing?