Skip to content

Instantly share code, notes, and snippets.

@martinandersen3d
Created March 16, 2021 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinandersen3d/2abc4609f0214743065af5225bb3acc6 to your computer and use it in GitHub Desktop.
Save martinandersen3d/2abc4609f0214743065af5225bb3acc6 to your computer and use it in GitHub Desktop.
Javascript Typesafe Class
class Person {
constructor() {
this.data = {};
}
get first() {
return this.data.first || 'UNKNOWN';
};
set first(name) {
if( typeof name === 'string' || name instanceof String ){
this.data.first = name;
}
else if(name === null ){
throw new Error('Expected String: Got Null')
}
else{
throw new Error('Not a string!')
}
};
}
var p = new Person();
console.log(p.first); // UNKNOWN
p.first = 'Hugo';
console.log(p.first); // Hugo
p.first = null;
//> Error: Expected String: Got Null
p.first = 1;
//> Error: Not a string!
// function isString(value) {
// return typeof value === 'string' || value instanceof String;
// }
// isString(''); // true
// isString(1); // false
// isString({}); // false
// isString([]); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment