我正在阅读手册的Classes部分,但有一个差异让我感到困惑。
在以下示例中:
在示例1中,他们首先显式地写出了返回类型
this is Networked & this
。我能理解这部分。
然后,在示例2中,他们只做了
this is { value: T }
,但是box
块中if
的类型是Box<string> & { value: string; }
。
我不知道为什么第二种情况有效。根据第一个示例,我希望它应该是
this is { value: T } & this
。这是否意味着我总是可以省略明确的& this
?
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
}
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.
}
尝试一下以防万一:是的,你可以省略
this
。类型保护始终在 this
实例上执行,缩小版本始终是 this
的某种变体,Typescript 足够智能来做到这一点。
与
Extract
作用相同
https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union