npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

typescript-object-validator

v1.1.1

Published

TypeScript first object validator

Downloads

2,555

Readme

Typescript Object Validator

A simple library for typescript projects to validating object shapes. You can use this package to declare the shape you'd like an object to align to. This is handy when you have a complex object (for example, an API response) and want to validate the object, AND have typescript recognize the shape.

Basic Usage

import { validateObjectShape } from 'typescript-object-validator'

const elephantValidation = validateObjectShape(
    'Elephant API response' // https://elephant-api.herokuapp.com/elephants/random
    randomElephantResponse,
    {
        _id: 'string',
        index: 'number',
        name: 'string',
        affiliation: 'string',
        species: 'string',
        sex: 'string',
        fictional: 'boolean',
        dob: 'string',
        dod: 'string',
        wikilink: 'string',
        image: 'string',
        note: 'string',
    }
)

if (elephantValidation.valid === true) {

    /*
        At this point, elephantValidation.result will have the type of:
        {
            _id: 'string',
            index: 'number',
            name: 'string',
            affiliation: 'string',
            species: 'string',
            sex: 'string',
            fictional: 'boolean',
            dob: 'string',
            dod: 'string',
            wikilink: 'string',
            image: 'string',
            note: 'string',
        }
    */

    console.log(elephantValidation.result.name)
    // -> "Packy"
}

API

validateObjectShape Can be used to validate an object:

import { validateObjectShape } from 'typescript-object-validator'

validateObjectShape(
    objectDescription,
    validationItem,
    expectedObjectShape,
    validationOptions
)
  • objectDescription (required - string): A description which is used in error messages when the object does not validate
  • validationItem (required - object): An object you want to validate
  • expectedObjectShape (required - object): A definition of what shape the object should match
  • validationOptions (required - object): A set of options to change the validation behaviour, see more

The result of the validation is an object with a valid property which flags if the validation succeeded or failed, a result object which is the validated and typed object, or an errors array with error results.

const validationResult = validateObjectShape(
    objectDescription,
    validationItem,
    expectedObjectShape,
    validationOptions
)

// If the validation is successful
{
    valid: true,
    result: { ...validatedItem }  // (the object you passed in, but typed!)
}

// If the validation fails
{
    valid: false,
    errors: [
        'Expected Test obj.two to be type: number, was string',
    ]
}

validateObjectShape will coerce values for you if it's able to. For example if you say the property age is a number, but it's passed in as a string, validateObjectShape will try convert it to a number for you in the result object:

const validationResult = validateObjectShape(
    'Coercion Example',
    { age: '30' },
    { age: number }
)

if (validationResult.valid === true) {
    // validationResult.result.age -> 30
    typeof validationResult.result.age === 'number'
}

The library also alows you to test nested objects and arrays, for example:

const validationResult = validateObjectShape(
    'Nested Example',
    {
        age: '30',
        meta: { group: 'Staff' }
        names: [
            { fname: 'Jeff', lname: 'Thompson' },
            { fname: 'Jeff', lname: 'Thompson' }
        ]
    },
    {
        age: number,
        meta: { group: 'string' }
        names: arrayOf({ fname: 'string', lname: 'string' })
    }
)

Validation Types

There are a number of basic validation types available to use, and some helpers which allow you build more complex types:

Basic types

  • string: Matches a string
  • number: Matches a number
  • boolean: Matches a boolean
  • unknown: Matches an unknown type (will skip validation on that property)

This package also understands more complex types such as arrays and optional types. You can import helper functions to assist you in building these.

Complex Types:

  • arrayOf ('string'): Array of some basic type
  • optional ('string'): Makes the property your testing optional. The test will only run if the property exists
const result = validateObjectShape(
    'Test obj',
    {
        one: 'string value',
        two: 2,
        three: true,
        four: ['1', '2'],
        five: [true, false],
        six: [1, 2],
        seven: 'whatever'
    },
    {
        one: 'string',
        two: 'number',
        three: 'boolean',
        four: arrayOf('string'),
        five: arrayOf('boolean'),
        six: arrayOf('number'),
        seven: 'unknown',
        eight: optional('boolean')
    }
)

Options

  • coerceValidObjectIntoArray (boolean): If you are validating an array with arrayOf, setting this to true will convert those properties to arrays for you, rather than returning an error. This is useful for example when converting from xml to json.
const validationResult = validateObjectShape(
    'Coercion Example',
    { names: { fname: 'Jeff', lname: 'Thompson' } },
    { names: arrayOf({ fname: 'string', lname: 'string' }) },
    { coerceValidObjectIntoArray: true }
)

/*
    Converts names into an array. validationResult.result:
    { names: [{ fname: 'Jeff', lname: 'Thompson' }] }
*/