Created
April 30, 2022 16:48
-
-
Save alexsoyes/e62f4356b64c5566df19d80b9a469163 to your computer and use it in GitHub Desktop.
Anemic Model in TypeScript with Object Validation
This file contains hidden or 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
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