Skip to content

Instantly share code, notes, and snippets.

@ProgrammingFire
Last active January 15, 2022 14:33
Show Gist options
  • Save ProgrammingFire/370b67d3ec8cfdeaaa508ed1b28f1c03 to your computer and use it in GitHub Desktop.
Save ProgrammingFire/370b67d3ec8cfdeaaa508ed1b28f1c03 to your computer and use it in GitHub Desktop.
Type Safety In JavaScript
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