Last active
April 16, 2019 02:37
-
-
Save rileyhilliard/2b1ae40fbc6bad8a62e0b4672a6d87ba to your computer and use it in GitHub Desktop.
TypeScript Class Destructure
This file contains 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
interface GeoInterface { | |
state: string; | |
country: string; | |
} | |
interface PersonInterface { | |
first: string; | |
last: string; | |
// a Person must contain a 'geo' object that matches | |
// the defined GeoInterface structure | |
geo: GeoInterface; | |
} | |
export default class Person { | |
public first: string; | |
public last: string; | |
private geo: GeoInterface; | |
// Enforce that the Class is being instantiated with a | |
// <PersonInterface> object, then destructure off the | |
// props that we want to use for our Person instance and assign | |
// them to the Classes props | |
constructor({ first, last, geo }: PersonInterface) { | |
Object.assign(this, { first, last, geo }); | |
} | |
// Adds .fullName property onto the <:Person> | |
// class instance | |
public get fullName(): string { | |
return `${this.first} ${this.last}`; | |
} | |
// Adds .location property onto the <:Person> | |
// class instance that returns a formatted location | |
public get location(): string { | |
const { state, country} = this.geo; | |
return `${state}, ${country}`; | |
} | |
// Simple example method that uses the Classes internal state | |
// to return info about the Person instance | |
whoAmI(): string { | |
const { fullName, location } = this; | |
return `My name is ${fullName}, and I'm from ${location}`; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment