我正在阅读手册的Classes部分,但有一个差异让我感到困惑.
在以下示例中:
-
在实施例1中,他们首次显式地编写了返回类型
this is Networked & this
.这部分我能理解. -
然后,在实施例2中,他们只做了
this is { value: T }
,但if
块中box
的类型是Box<string> & { value: string; }
.
我不知道为什么第二种情况有效.根据第一个例子,我预计应该是this is { value: T } & this
.这是否意味着我总是可以省略显式的& this
?
实施例1
class FileSystemObject {
isFile(): this is FileRep {
return this instanceof FileRep;
}
isDirectory(): this is Directory {
return this instanceof Directory;
}
isNetworked(): this is Networked & this { // the return type here.
return this.networked;
}
constructor(public path: string, private networked: boolean) {}
}
class FileRep extends FileSystemObject {
constructor(path: string, public content: string) {
super(path, false);
}
}
class Directory extends FileSystemObject {
children: FileSystemObject[];
}
interface Networked { // this interface that matters.
host: string;
}
const fso: FileSystemObject = new FileRep("foo/bar.txt", "foo");
if (fso.isFile()) {
fso.content;
} else if (fso.isDirectory()) {
fso.children;
} else if (fso.isNetworked()) {
fso.host; // const fso: Networked & FileSystemObject
}
实施例2
class Box<T> {
value?: T;
hasValue(): this is { value: T } { // here, there is no `& this`.
return this.value !== undefined;
}
}
const box = new Box<string>();
box.value = "Gameboy";
if (box.hasValue()) {
box.value; // notice the type of box here.
}