diff --git a/example.html b/example.html index eb6833a..a4c28f2 100644 --- a/example.html +++ b/example.html @@ -1,4 +1,5 @@ + + + diff --git a/runtime-checker.js b/runtime-checker.js index cf25a41..bd0f7b7 100644 --- a/runtime-checker.js +++ b/runtime-checker.js @@ -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)); + } + } + }); +} +