type predicate
this-based type guards (
this is ยซTยป
)
๐ discriminated union
// โญ๏ธ type predicate: ยซparamยป is ยซTยป
// ยซparamยป : parameter name of current function
// ยซTยป : a type
// โญ type predicate โฎ โญ๏ธ
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
// both calls to 'swim' and 'fly' are now okay.
let pet = getPet();
if (isFish(pet)) pet.swim();
else pet.fly();
class FileSystemObject {
// this-based type guard
// โญ this-is type guard โฎ โญ๏ธ
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()) {
fso.content;
const fso: FileRep
} else if (fso.isDirectory()) {
fso.children;
const fso: Directory
} else if (fso.isNetworked()) {
fso.host;
const fso: Networked & FileSystemObject
}
Last updated