Last active
January 15, 2022 14:33
-
-
Save ProgrammingFire/370b67d3ec8cfdeaaa508ed1b28f1c03 to your computer and use it in GitHub Desktop.
Type Safety In JavaScript
This file contains 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 Variable { | |
type; | |
value; | |
freeze; | |
constructor(value, type, freeze = false) { | |
if (!type) { | |
this.type = typeof value; | |
} else { | |
this.type = type; | |
} | |
this.set(value); | |
this.freeze = freeze; | |
} | |
get() { | |
return this.value; | |
} | |
set(value) { | |
if (this.freeze) { | |
throw new Error("Cannot set value of a frozen variable"); | |
} | |
if (this.type === "any") { | |
this.value = value; | |
return; | |
} | |
if (Array.isArray(this.type)) { | |
if (!this.type.includes(typeof value)) { | |
throwError(this.type, value); | |
} | |
} else { | |
if (typeof value !== this.type) { | |
throwError(this.type, value); | |
} | |
} | |
this.value = value; | |
function throwError(type, value) { | |
throw new Error( | |
`Cannot set value of variable to ${typeof value} of type ${ | |
Array.isArray(type) ? type.join(", ") : type | |
}` | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment