Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active February 8, 2022 16:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathansmith/04650335be7c5d57eb475e9c265e280a to your computer and use it in GitHub Desktop.
Save nathansmith/04650335be7c5d57eb475e9c265e280a to your computer and use it in GitHub Desktop.
TypeScript example, for a friend. Explaining types, interfaces, and tuples.
// 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