this-based type guards

TypeScript 1.8 extends user-defined type guard functions to class and interface methods.

this is T is now valid return type annotation for methods in classes and interfaces.When used in a type narrowing position (e.g. if statement), the type of the call expression target object would be narrowed to T.

Example
  1. class FileSystemObject {
  2. isFile(): this is File { return this instanceof File; }
  3. isDirectory(): this is Directory { return this instanceof Directory;}
  4. isNetworked(): this is (Networked & this) { return this.networked; }
  5. constructor(public path: string, private networked: boolean) {}
  6. }
  7. class File extends FileSystemObject {
  8. constructor(path: string, public content: string) { super(path, false); }
  9. }
  10. class Directory extends FileSystemObject {
  11. children: FileSystemObject[];
  12. }
  13. interface Networked {
  14. host: string;
  15. }
  16. let fso: FileSystemObject = new File("foo/bar.txt", "foo");
  17. if (fso.isFile()) {
  18. fso.content; // fso is File
  19. }
  20. else if (fso.isDirectory()) {
  21. fso.children; // fso is Directory
  22. }
  23. else if (fso.isNetworked()) {
  24. fso.host; // fso is networked
  25. }