Parameter Type Safety in JavaScript
Today I got bit by a small but annoying bug due to the lack of type safety in javascript. I scrapped an experimental change to a method but forgot to remove the parameter from the function declaration. When I finally tracked it down I decided to solve this problem once and for all, without resorting to compiling TypeScript. I'm not a fan of their syntactic sugar. I just wanted a clean, simple way to check parameters in a declarative inline fashion. And I didn't like the look any libraries that I could find which claimed to handle this sort of thing. So I wrote my own that I feel is clean, elegant and intuitive. And instead of hoarding this knowledge for myself, I decided to share it. import { ValidatedMethod } from './validated-method.js'; class UserService { createUser = new ValidatedMethod({ username: 'string', age: 'number', active: 'boolean', roles: 'array', settings: 'object', email: ['string', 'null'], birthday: 'optional', title: 'string' }, async (opts) => { // Parameters are validated, safe to use return await db.users.create(opts); }); } const myService = new UserService(); myService.createUser({ username: 'goober', age: 40, active: true, roles: [ 'user', 'editor' ], settings: { darkmode: 'auto' }, email: null, // birthday: is optional so undefined is ok // Throw TypeError because title: is undefined }); A full suite of tests are in the repo. If anyone runs into a use-case that they feel warrants attention, just let me know and I'll look into it.

Today I got bit by a small but annoying bug due to the lack of type safety in javascript. I scrapped an experimental change to a method but forgot to remove the parameter from the function declaration.
When I finally tracked it down I decided to solve this problem once and for all, without resorting to compiling TypeScript. I'm not a fan of their syntactic sugar. I just wanted a clean, simple way to check parameters in a declarative inline fashion. And I didn't like the look any libraries that I could find which claimed to handle this sort of thing. So I wrote my own that I feel is clean, elegant and intuitive. And instead of hoarding this knowledge for myself, I decided to share it.
import { ValidatedMethod } from './validated-method.js';
class UserService {
createUser = new ValidatedMethod({
username: 'string',
age: 'number',
active: 'boolean',
roles: 'array',
settings: 'object',
email: ['string', 'null'],
birthday: 'optional',
title: 'string'
}, async (opts) => {
// Parameters are validated, safe to use
return await db.users.create(opts);
});
}
const myService = new UserService();
myService.createUser({
username: 'goober',
age: 40,
active: true,
roles: [ 'user', 'editor' ],
settings: { darkmode: 'auto' },
email: null,
// birthday: is optional so undefined is ok
// Throw TypeError because title: is undefined
});
A full suite of tests are in the repo. If anyone runs into a use-case that they feel warrants attention, just let me know and I'll look into it.