Skip to content

Instantly share code, notes, and snippets.

@rileyhilliard
Last active April 16, 2019 02:37
Show Gist options
  • Save rileyhilliard/2b1ae40fbc6bad8a62e0b4672a6d87ba to your computer and use it in GitHub Desktop.
Save rileyhilliard/2b1ae40fbc6bad8a62e0b4672a6d87ba to your computer and use it in GitHub Desktop.
TypeScript Class Destructure
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