Add typed variables
This commit is contained in:
		
							parent
							
								
									9faf3c9260
								
							
						
					
					
						commit
						56b3971e1a
					
				
							
								
								
									
										10
									
								
								example.html
									
									
									
									
									
								
							
							
						
						
									
										10
									
								
								example.html
									
									
									
									
									
								
							| @ -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> | ||||
| 
 | ||||
|  | ||||
| @ -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)); | ||||
| 			} | ||||
| 		} | ||||
| 	}); | ||||
| } | ||||
| 
 | ||||
|  | ||||
		Loading…
	
		Reference in New Issue
	
	Block a user