检测 Typescript 类方法中的正确条件返回类型
我找到了类似的问题:在 TypeScript 的类方法中使用类型谓词
但是答案并不包括返回一个值。例如,我想做的事情相当简单:
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)');
}
基本上,如果你调用 hasMatch,则 getMatch 的值是一个字符串,否则它是 undefined。
我尝试了几件不同的事情:
使用
assert:public hasMatch(): asserts this is { getBestMatch(): string } {,但是在尝试返回值时出现以下类型问题:类型 'boolean' 不能分配给类型 'void'。使用相同的语法,不使用
assert(这是别人对另一个问题的评论之一):public hasMatch(): this is ResolveAcceptLanguage & { getBestMatch(): string } {但它不起作用。看起来像是在添加一个重载(在 VScode 中),但我看不到…
有没有一种方法可以在我提供的示例中不使用 as string 来实现?
答案#1
总而言之,今天用 TypeScript 这是不可行的。
@catgirlkelly 提供了一些有趣的解决方法可以尝试,但每种方法都有不同的缺点(即便它们有效时)。
- https://tsplay.dev/mb0ePw
- https://tsplay.dev/w2aOxW
- https://tsplay.dev/WoGdjW
但正如我们可以从我在 TypeScript 的 GitHub 上提交的问题中看到的,自至少 2016 年以来,关于这个话题类似的问题已经被提出,并且由于复杂性,尚未提供解决方案。