Skip to content

Instantly share code, notes, and snippets.

@alexsoyes
Created April 30, 2022 16:48
Show Gist options
  • Save alexsoyes/e62f4356b64c5566df19d80b9a469163 to your computer and use it in GitHub Desktop.
Save alexsoyes/e62f4356b64c5566df19d80b9a469163 to your computer and use it in GitHub Desktop.
Anemic Model in TypeScript with Object Validation
class User {
private _name: string;
constructor() {}
set name(name: string) {
this._name = name;
}
get name(): string {
return this._name;
}
}
const user = new User();
// ... later on the code
user.name.toUpperCase(); // TypeError: user._name is undefined
class User {
// name is mandatory is, we will always have a name.
constructor(private _name: string) {
if (_name?.length < 2) {
throw new Error('Name is mandatory');
}
}
get name(): string {
return this._name;
}
}
const user = new User('Alex');
user.name.toUpperCase(); // will always work
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment