Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Created November 2, 2020 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save topherPedersen/878d045676deca769491cbe052f10e1a to your computer and use it in GitHub Desktop.
Save topherPedersen/878d045676deca769491cbe052f10e1a to your computer and use it in GitHub Desktop.
TypeScript Union Type Demo
// DEMO: Using Union-Types in TypeScript
// Question: What are Union Types???
// Answer: Union Types are TypeScript types which can be equal to many different types which often share 'union' properties amongst the various different types. For example, an Athlete Union-Type could be used to represent FootballPlayer, BasketballPlayer, and BaseballPlayer types
type FootballPlayer = {
firstName: string,
lastName: string,
jerseyNumber: number,
sport: string,
touchdowns: number,
};
type BasketballPlayer = {
firstName: string,
lastName: string,
jerseyNumber: number,
sport: string,
points: number,
};
type BaseballPlayer = {
firstName: string,
lastName: string,
jerseyNumber: number,
sport: string,
hits: number,
};
type Athlete = BaseballPlayer | BasketballPlayer | FootballPlayer;
const quarterback: Athlete = {
firstName: "Ben",
lastName: "DiNucci",
jerseyNumber: 7,
sport: 'Football',
touchdowns: 0,
};
function displayStats(athlete: Athlete) {
switch(athlete.sport) {
case "Football":
// NOTE: We can access shared 'union' properties such as firstName,
// lastName, jerseyNumber, and sport using 'athlete' which is of the
// union type 'Athlete'
console.log("Player: " + athlete.firstName + " " + athlete.lastName);
// HOWEVER: If we want to access a non-union-type property such as
// touchdowns, we cannot use 'athlete' which is of the union type
// 'Athlete'. Attempting to call athlete.touchdowns will crash the app.
// Instead, we need to type-cast athlete as FootballPlayer if we wish
// to access the 'touchdowns' property
let footballPlayer: FootballPlayer = athlete as FootballPlayer;
console.log("Touchdowns: " + footballPlayer.touchdowns.toString());
break;
case "Basketball":
console.log("Player: " + athlete.firstName + " " + athlete.lastName);
let basketballPlayer: BasketballPlayer = athlete as BasketballPlayer;
console.log("Points: " + basketballPlayer.points.toString());
break;
case "Baseball":
console.log("Player: " + athlete.firstName + " " + athlete.lastName);
let baseballPlayer: BaseballPlayer = athlete as BaseballPlayer;
console.log("Hits: " + baseballPlayer.hits.toString());
break;
default:
console.log("Error: Something went wrong...");
}
}
displayStats(quarterback);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment