Add typed variables

This commit is contained in:
ReimarPB 2023-09-09 14:20:03 +02:00
parent 9faf3c9260
commit 56b3971e1a
2 changed files with 29 additions and 0 deletions

View File

@ -1,4 +1,5 @@
<script src="runtime-checker.js"></script>
<script>
const sum = typedFunction((a_number, b_number) => {
return a + b;
@ -8,5 +9,14 @@
console.log(result); // 3
sum("1", 2); // Error
</script>
<script>
typedVar("test", 5);
test = 6;
test = "a string"; // Error
</script>

View File

@ -59,3 +59,22 @@ window.typedFunction = function(func) {
return func.addRuntimeChecker();
}
window.typedVar = function(name, value) {
function getTypeName(type) {
return typeof type === "function" ? type.name : typeof type;
}
var scope = typedVar.caller || window;
Object.defineProperty(scope, name, {
set: function(newValue) {
if (
(typeof value === "function" && !(newValue instanceof value)) ||
(typeof value !== "function" && typeof newValue !== typeof value)
) {
throw new Error("Cannot assign value of type " + getTypeName(newValue) + " to variable " + name + " of type " + getTypeName(value));
}
}
});
}