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.

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay