Skip to content

Instantly share code, notes, and snippets.

@Ibro
Last active March 27, 2017 18:35
Show Gist options
  • Save Ibro/813808abf395e7bacd422b8053b88d88 to your computer and use it in GitHub Desktop.
Save Ibro/813808abf395e7bacd422b8053b88d88 to your computer and use it in GitHub Desktop.
Type guarding in TypeScript
class Student {
study() {
}
}
class Professor {
teach() {
}
}
function getPerson(n: number): Student | Professor {
if (n === 1) {
return new Student();
} else {
return new Professor();
}
}
let person: Student | Professor = getPerson(1);
if (person instanceof Student) {
person.study(); // OK
} else {
// person.study(); // Error, person is of type Professor here.
// so compiler recognizes we can call function teach()
person.teach();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment