Last active
February 8, 2022 16:22
-
-
Save nathansmith/04650335be7c5d57eb475e9c265e280a to your computer and use it in GitHub Desktop.
TypeScript example, for a friend. Explaining types, interfaces, and tuples.
This file contains hidden or 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
// Possible `gender` values. | |
type Gender = 'male' | 'female' | 'other' | |
// Generic `person` interface. | |
interface IPerson { | |
// Specific string. | |
gender: Gender | |
// Any string. | |
name: string | |
// `?` means optional. | |
mother?: IMother | |
father?: IFather | |
} | |
// Biological `mother` interface. | |
interface IMother extends IPerson { | |
gender: 'female' | |
} | |
// Biological `father` interface. | |
interface IFather extends IPerson { | |
gender: 'male' | |
} | |
// Tuple for parents. | |
type IParents = [IMother, IFather] | |
// Method to get `[mom, dad]`. | |
const getParents = (person: IPerson) => { | |
// Cast return value as tuple. | |
return [person.mother, person.father] as IParents | |
} | |
// Define myself. | |
const Nathan: IPerson = { | |
name: 'Nathan', | |
gender: 'male', | |
mother: { | |
name: 'Elise', | |
gender: 'female' | |
}, | |
father: { | |
name: 'Yoshio', | |
gender: 'male' | |
} | |
} | |
// Alias my parents. | |
const [myMom, myDad] = getParents(Nathan) | |
// logs: "Elise". | |
console.log(myMom.name) | |
// logs: "Yoshio". | |
console.log(myDad.name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment