Skip to content

Instantly share code, notes, and snippets.

@mathieuancelin
Created February 3, 2016 08:09
Show Gist options
  • Save mathieuancelin/8bdba6b630b3aaf4899d to your computer and use it in GitHub Desktop.
Save mathieuancelin/8bdba6b630b3aaf4899d to your computer and use it in GitHub Desktop.
function Person(firstName: string, lastName: string, age: number) {
if (!this) return new Person(firstName, lastName, age); // if no new, then new to have type
return Object.freeze(Object.assign(this || {}, { // assign is use of enhance this, to have type
copy(obj) {
const values = { firstName, lastName, age, ...obj };
return new Person(values.firstName, values.lastName, values.age);
},
get firstName() {
return firstName;
},
get lastName() {
return lastName;
},
get age() {
return age;
},
toString() {
return `Person(${firstName}, ${lastName}, ${age})`;
}
}));
}
const person1 = Person('John', 'DOE', 42)
const person2 = new Person('Jane', 'DOE', 42);
const person3 = person1
.copy({ firstName: 'Billy' })
.copy({ age: '28' });
console.log(person1.toString());
console.log(person2.toString());
console.log(person3.toString());
person1.hello = 'hello'; // will not work
person1.firstName = 'Eugene'; // will not work
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment