DEV Community

Luke Harold Miles
Luke Harold Miles

Posted on

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)