为什么在 TypeScript 中将类型保护的返回类型写为 `this is (...) & this`?

问题描述 投票:0回答:1

我正在阅读手册的Classes部分,但有一个差异让我感到困惑。

在以下示例中:

  1. 示例1中,他们首先显式地写出了返回类型

    this is Networked & this
    。我能理解这部分。

  2. 然后,在示例2中,他们只做了

    this is { value: T }
    ,但是
    box
    块中
    if
    的类型是
    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.
}

typescript typeguards
1个回答
0
投票

尝试一下以防万一:是的,你可以省略

this
。类型保护始终在
this
实例上执行,缩小版本始终是
this
的某种变体,Typescript 足够智能来做到这一点。

看起来效果和

Extract

一样

https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union

© www.soinside.com 2019 - 2024. All rights reserved.