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-field-validation

v2.0.3

Published

NonNullbale type manipulation and validaton

Downloads

15

Readme

typescript-field-validation

Build Status

Basic tools for NonNullable type manipulation and validation.

There are two tools exposed in this library which are designed to work together:

  • SetRequired (conditional type)
  • validate (function)

SetRequired allows you to take a type and declare fields to be Required and NonNullable.

validate checks if the required fields are present and not null or undefined.

Both SetRequired and validate use the same syntax for requiring fields. This means you can perform type manipulations and data validation by decalring the required fields once.

Syntax

To specify a field as being required simply use that fields name. To specify a sub field on a field use dot notation field.subField. To specify a required field for every object in a field that is an array use []. For example fieldOne[].subField would mean that fieldOne is an array and every member of that array needs to have a subField.

Example usage

import { validate, SetRequired } from 'typescript-field-validation';

type TypeWithOptionalFields = {
  id?: string;
  item?: {
    items?: { id?: string; value: any | null }[];
  };
  link?: string;
  date?: number;
};

const requiredFields = ['id', 'item.items[].id', 'item.items[].value', 'date'] as const;

type TypeWithNonOptionFields = SetRequired<TypeWithOptionalFields, typeof requiredFields[number]>;

const invalidData = {
  id: '12345',
  item: {
    items: [{ value: 'hello world' }],
  },
};

// Default: Provides maximum information regarding what fields were missing
const result1 = validate(invalidData, requiredFields);
console.log('Default', result1);
/**
{
  invalidFields: { date: 'is missing', 'item.items[0].id': 'is missing' },
  validType: null
}
 */

// No index: Removes the array index for missing fields.
const result2 = validate(invalidData, requiredFields, {
  includeIndex: false,
});
console.log('No array index', result2);
/**
{
  invalidFields: { date: 'is missing', 'item.items[].id': 'is missing' },
  validType: null
}
*/

// Fail fast: Returns the first failure at the lowest depth
const result3 = validate(invalidData, requiredFields, {
  failFast: true,
});
console.log('Fail fast', result3);
/**
 { invalidFields: { date: 'is missing' }, validType: null }
 */

// Raw fields: Returns an error object whose shape mimicks the data
const result4 = validate(invalidData, requiredFields, {
  rawFields: true,
});
console.log('Raw fields', JSON.stringify(result4, null, 2));
/**
 {
  "invalidFields": {
    "date": "is missing",
    "item": {
      "items": [
        {
          "id": "is missing"
        }
      ]
    }
  },
  "validType": null
}
 */

const validData = {
  id: '12345',
  item: {
    items: [{ id: 'myId', value: 'hello world' }],
  },
  date: 1627787814504,
};

const result5: TypeWithNonOptionFields | null = validate(validData, requiredFields).validType;

if (result5) {
  console.log('Result is valid type: 'true);
  // true
}

A note of warning: This tool does not check that the values of the required fields are of the type defined by the base type, this is assumed to be correct. Rather, it simply makes a field required and removes undefined | null from the fields union type.

CHANGELOG

  • 2.0.3: Fix: Missing array items keep their index when previous elements passed

  • 2.0.2: Inlining of small helper functions to minimize code

  • 2.0.1: Fix: failFast option returns single result for array fields

  • 2.0.0:

    • validate function uses a breadth first search over a generated search graph
    • validate function takes additional parameters to failFast and other formatting options of error messages

    Breaking changes:

    • Package now targets es2019
    • validate now returns missing fields as a Record<field, error message>
    • validate now optionally returns missing fields in the same shape as the provided data when the rawFields option is set to true.
  • 1.1.2: Add MIT license

  • 1.1.1: Update Result type to be a exclusive or union of pass or fail types

  • 1.1.0: Improve error messages and add additional checks for object vs array fields

  • 1.0.1: Update readme