Type type masks can be used to limit the type of prof parameter .
export interface AuthenticatedProfile {
readonly userId: string;
readonly name: string;
}
export interface AnonymousProfile {
readonly userId: undefined;
readonly otherProp: string;
}
export type Profile = AnonymousProfile | AuthenticatedProfile;
function isAuthenticatedProfile(prof: Profile): prof is AuthenticatedProfile {
return (<AuthenticatedProfile>prof).name !== undefined;
}
function isAnonymousProfile(prof: Profile): prof is AnonymousProfile {
return (<AnonymousProfile>prof).otherProp !== undefined;
}
function handleProfile(prof: Profile) {
if (isAuthenticatedProfile(prof)) {
console.log(prof.name);
} else if (isAnonymousProfile(prof)) {
console.log(prof.otherProp);
}
}
typescript handbook.