0

straight from the official TSC docs, I have a question: What does the "& this" do in the line containing isNetworked()?

Thanks in advance and cheers

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;
}

src: this-based type guards - TypeScript Docs

Programmosaurus
  • 111
  • 1
  • 8
  • 1
    It's an [intersection](//www.typescriptlang.org/docs/handbook/2/objects.html#intersection-types); the type `A & B` is assignable to `A` and `B`. TS requires that type predicate return a type that's assignable to the input type; `this is Networked` would be rejected because `Networked` is not necessarily assignable to` this`. But `Networked & this` will definitely be narrower than `this` so it works. So it's saying "after the narrowing, `this` will be seen as `this` *and* `Narrowed`". Does that fully address the question? If so I'll write up an answer explaining; if not, what am I missing? – jcalz Aug 09 '23 at 16:46
  • @jcalz "*TS requires that type predicate return a type that's assignable to the input type; `this is Networked` would be rejected*" - ah, that's the non-obvious part I had missed as well. – Bergi Aug 09 '23 at 17:03

0 Answers0