Created
March 16, 2021 20:09
-
-
Save martinandersen3d/2abc4609f0214743065af5225bb3acc6 to your computer and use it in GitHub Desktop.
Javascript Typesafe Class
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 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