Last active
March 27, 2017 18:35
-
-
Save Ibro/813808abf395e7bacd422b8053b88d88 to your computer and use it in GitHub Desktop.
Type guarding in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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