Skip to content

Instantly share code, notes, and snippets.

@Chester97
Created January 22, 2021 10:53
Show Gist options
  • Save Chester97/9f05411cf32dd7e1032e712a4f2446a8 to your computer and use it in GitHub Desktop.
Save Chester97/9f05411cf32dd7e1032e712a4f2446a8 to your computer and use it in GitHub Desktop.
interface User {
name: string;
age: number;
occupation: string;
}
interface Admin {
name: string;
age: number;
role: string;
}
function isAdmin(person: Person): person is Admin {
return 'role' in person;
}
export type Person = User | Admin;
export const persons: Person[] = [
{
name: 'Max Mustermann',
age: 25,
occupation: 'Chimney sweep'
},
{
name: 'Jane Doe',
age: 32,
role: 'Administrator'
},
{
name: 'Kate Müller',
age: 23,
occupation: 'Astronaut'
},
{
name: 'Bruce Willis',
age: 64,
role: 'World saver'
}
];
export function logPerson(person: Person) {
let additionalInformation: string;
if ('role' in person) {
additionalInformation = person.role;
} else {
additionalInformation = person.occupation;
}
console.log(` - ${person.name}, ${person.age}, ${additionalInformation}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment