DEV Community

Discussion on: JavaScript Type Checking... Without TypeScript

Collapse
 
johncarroll profile image
John Carroll • Edited

Interesting read. It seems like you, very intentionally, created a small (and, I imagine, performant), tool for some quick type checking. I'm guessing this is all you need. But! In case you aren't aware (because I wasn't), there's a validation/type-checking pattern that I call the "decoder" pattern (I'm not sure what the "official" name is) that I've found to be super (!) useful because of its composability.

For example:

import { assert } from 'ts-decoders';
import { objectD, stringD, predicateD, arrayD, nullableD, numberD  } from 'ts-decoders/decoders';

const nonBlankStringD = stringD().chain(
  predicateD(input => input.length > 0, { errorMsg: "cannot be blank" })
);

const myParamValidator = assert(
  objectD({
    id: nonBlankStringD,
    values: arrayD( nullableD(numberD()) ),
  }),
);

// Awesome, this passes
myParamValidator({ id: "apple", values: [1, null] });

// Oops! Throws error with message:
// "must be an object"
myParamValidator("a string value");

// Oops! Throws error with message:
// "invalid value for key [\"id\"] > cannot be blank"
myParamValidator({ id: "", values: [] });

// Oops! Throws error with message:
// "invalid value for key [\"values\"] > invalid value for key [2] > must be a number or null"
myParamValidator({ id: "apple", values: [1, null, "3"] });

// Oops! Throws error:
// "cannot be blank"
assert(nonBlankStringD)("");
Enter fullscreen mode Exit fullscreen mode

This example uses the library I made for this purpose, ts-decoders, but more popular options are libraries like yup or io-ts.

The decoder pattern does add a bit of complexity though, so I can understand if it's not appropriate for your use case. The decoder composability is very nice though, so figured I'd mention it in a conversation about type-checking.

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

I knew that there were libraries/packages out there, although I can't claim to have seen this particular pattern. Looks pretty solid! I'd probably be most interested in yup since I'm not really a fan of TS.

Thanks for cluing me into this!