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

在以下示例中:

  1. 实施例1中,他们首次显式地编写了返回类型this is Networked & this.这部分我能理解.

  2. 然后,在实施例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.
}

推荐答案

为了以防万一,try 了一下:是的,您可以省略this.类型保护始终在this实例上执行,缩小版本始终是this的某个变体,类型脚本足够聪明可以做到这一点.

工作原理与Extract相同

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

Typescript相关问答推荐

为什么在TypScript中将类型守护的返回类型写成This is(

等待的R没有用响应对象展开到R

Angular 过滤器形式基于某些条件的数组控制

界面中这种类型的界面界面中的多态性

是否可以根据嵌套属性来更改接口中属性的类型?

在Typescribe中,extends工作,但当指定派生给super时出错""

Angular 信号:当输入信号改变值时,S触发取数的正确方式是什么?

编剧错误:正在等待Expect(Locator).toBeVisible()

Express Yup显示所有字段的所有错误

如何以Angular 形式显示验证错误消息

类型,其中一条记录为字符串,其他记录为指定的

在Reaction-Native-ReAnimated中不存在Animated.Value

ANGLING v17 CLI默认设置为独立:延迟加载是否仍需要@NgModule进行路由?

防止重复使用 Select 器重新渲染

我在Angular 17中的environment.ts文件中得到了一个属性端点错误

判断映射类型内的键值的条件类型

如何在不违反挂钩规则的情况下动态更改显示内容(带有状态)?

在抽象类构造函数中获取子类型

编剧- Select 动态下拉选项

Angular另一个组件的nativeelement未定义