sylvainpolletvillard / ObjectModel

Strong Dynamically Typed Object Modeling for JavaScript
http://objectmodel.js.org
MIT License
467 stars 30 forks source link

Proposal: Any Model #106

Closed sylvainpolletvillard closed 5 years ago

sylvainpolletvillard commented 5 years ago

The closest thing you can get for a 'any' type in ObjectModel is to specify all primitives types plus the object type: [Boolean, Number, String, Symbol, undefined, null, Object]. It works but it's a bit verbose, and not the best thing we can do for performance.

Proposal 1

This proposal aims to introduce a Any model that would basically skip any validation for the value.

import { Any } from "objectmodel";
const UserData = ObjectModel({ savedItem: Any })
const ArrayNotEmpty = ArrayModel(Any).assert(function isNotEmpty(arr) { 
   return arr.length > 0 
}).as("ArrayNotEmpty");
const Serializer = FunctionModel(Any).return(String);

Another use for this Any model would be to express a variable amount of parameters for functions. Function models in v3 lack a way of specifying functions that can take any amount of arguments, using the spread operator for example:

const Operation = FunctionModel().return(Number)
const sum = Operation((...args) => args.reduce((a,b) => a+b, 0))

sum(1,2,3)
// Uncaught TypeError: expecting 0 arguments for Function() => Number, got 3

Proposal 2

When using spread operator with Any, we could express that:

const Operation = FunctionModel(...Any).return(Number)

Proposal 3

It could also be possible to specify the type of any parameter:

const Operation = FunctionModel(...Any(Number)).return(Number)

Open to discuss about the needs and the syntax