Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created September 13, 2011 20:17
Show Gist options
  • Save rwaldron/1215024 to your computer and use it in GitHub Desktop.
Save rwaldron/1215024 to your computer and use it in GitHub Desktop.
TypedObject Constructor
(function( global ) {
global.TypedObject = function( obj ) {
var keys = Object.keys( obj || {} ),
len = keys.length,
data = {},
typeOf = {
// prop: type
},
k = -1;
if ( len ) {
while ( ++k < len ) {
var key = keys[ k ],
val = obj[ key ];
data[ key ] = val;
typeOf[ key ] = typeof val;
}
}
return Proxy.create({
get: function( r, name ) {
return data;
},
set: function( r, name, value ) {
var type = typeOf[ name ];
if ( !type ) {
type = typeOf[ name ] = typeof value;
}
if ( typeof value !== type ) {
throw new Error(
"Property value type mismatch for `" + name + "`: expected " + type + ", saw " + typeof value
);
}
data[ name ] = value;
}
}, Object.prototype );
};
})( this );
var o = new TypedObject();
o.foo = "string";
try {
o.foo = 1;
} catch(e) {
console.log( e );
// > "Property value type mismatch for `foo`: expected string, saw number
}
console.log( o );
o = new TypedObject({ foo: 1 });
console.log( o );
try {
o.foo = [];
} catch(e) {
console.log( e );
// > "Property value type mismatch for `foo`: expected number, saw object
}
@rwaldron
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment