Skip to content

基于类型守卫的this

你可以在类和接口的方法的返回位置使用 this is Type 。当与类型缩小混合时(例如if语句),目标对象的类型将被缩小到指定的Type。

typescript
class FileSystemObject { 
  isFile(): this is FileRep { 
    return this instanceof FileRep; 
  }
  isDirectory(): this is Directory { 
    return this instanceof Directory; 
  }
  isNetworked(): this is Networked & this { 
    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 { 
  host: string; 
}
const fso: FileSystemObject = new FileRep("foo/bar.txt", "foo"); 
if (fso.isFile()) { 
  // const fso: FileRep 
  fso.content; 
} else if (fso.isDirectory()) { 
  // const fso: Directory
  fso.children; 
} else if (fso.isNetworked()) { 
  // const fso: Networked & FileSystemObject 
  fso.host; 
}

基于 this 的类型保护的一个常见用例,是允许对一个特定字段进行懒惰验证。例如,这种情况下,当 hasValue 被验证为真时,就会从框内持有的值中删除一个未定义值。

typescript
class Box <T> { 
  value?: T; 
  
  hasValue(): this is { value: T} { 
    return this.value !== undefined; 
  } 
}
const box = new Box(); 
box.value = "Gameboy"; 

// (property) Box<unknown>.value?: unknownbox.value; 
if (box.hasValue()) { 
  // (property) value: unknown
  box.value; 
}