I found this similar questions: Using type predicates in class methods in TypeScript
But the answer does not include returning a value. For example, what I would like to do is fairly simple:
const resolver = new Resolver(data);
if (resolver.hasMatch()) {
// Invalid type "string | undefined" of template literal expression.
console.log(`This is the match: ${resolver.getMatch()}`);
} else {
console.log('`getMatch` returns `undefined` (no match)');
}
Basically, if you call hasMatch the value of getMatch is a string, otherwise it's undefined.
I tried a few different things:
using
assert:public hasMatch(): asserts this is { getBestMatch(): string } {but the following type problem occurs when trying to return a value:Type 'boolean' is not assignable to type 'void'.using the same syntax, without
assert(this was one of the comments on the other question):public hasMatch(): this is ResolveAcceptLanguage & { getBestMatch(): string } {but it does not work. It looks like it's adding an overload (in VScode) but I can't see it...
Is there a way to do this without using as string in the example I provided?