这是重现此内容的最小片段
class Stuff<InGuild extends boolean = boolean> {
public inGuild(): this is Stuff<true> {
return true;
}
}
const x = new Stuff();
if (x.inGuild()) {
x
}
将鼠标悬停在 VSCode 上的
x
上,我会看到以下内容:
x
仍然是Stuff<boolean>
而不是Stuff<true>
,为什么呢?
我从discord.js这里得到了这个想法,我想知道为什么他们可以这样做,但我无法在这里重现这个想法。
出于某种原因,需要以某种方式使用
InGuild
泛型,否则类型保护不起作用。
对于上面的代码,如果我们这样做:
class Stuff<InGuild extends boolean = boolean> {
// @ts-ignore
private readonly _cacheType: InGuild;
public inGuild(): this is Stuff<true> {
return true;
}
}
const x = new Stuff();
if (x.inGuild()) {
x // <-- Now x is correctly a Stuff<true>
}
前面提到的discord.js库也做到了这一点,示例1,示例2,示例3
我想也许我们的功能用例太小众/不寻常,但现在还有效。