DEV Community

Luke Miles
Luke Miles

Posted on

4 3

Simple typescript data validation without libraries

Check that your function arguments have correct types at run-time!

import {validate} from './validate'

const validGetUserArgs = Object.freeze({
    authToken: '',
    pubkey: new PublicKey()
    atTime:  new Date()
})

type GetUserArgs = typeof validGetUserArgs

function getUser(args: GetUserArgs) {
    validate(args, validGetUserArgs)
    checkToken(args.authToken)
    db.get({pubkey: args.pubkey, at: args.atTime})
}
Enter fullscreen mode Exit fullscreen mode

And here's one definition of that validate function:

function validate<T>(obj: T, valid: T) {
    for (const k in valid) if (!(k in obj)) throw Error(`missing key ${k}`)
    for (const k in obj) if (!(k in valid)) throw Error(`unknown key ${k}`)
    for (const k in obj) {
        const got = typeof obj[k]
        const wanted = typeof valid[k]
        if (got !== wanted) {
            throw Error(`argument ${k} had type ${got} instead of ${wanted}`)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Demo in typescript playground

Note this is limited. You'll have a headache with unions, optionals, nesting, non-class interfaces, etc.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up