JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 13
  • Score
    100M100P100Q36457F
  • License BSD-2-Clause

Check json value based of Typescript type in string

Package Exports

  • ts-type-check

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (ts-type-check) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

ts-type-check

Check json value based of Typescript type in string

npm Package Version

Example

import { checkTsType } from 'ts-type-check'

checkTsType('string', 'Alice');
// no error


checkTsType('{ UserId: string }', { UserId: 'Alice' });
// no error
checkTsType('{ UserId: string }', { UserId: 'Alice', Foo: 'bar' }, 'fail');
// throw exception complaining extra field `Foo`

More advanced type using nested object, |, and & are also supported.

import { checkTsType } from 'ts-type-check'


checkTsType(`'y' | 'n'`, 'n');
// no error
checkTsType(`1 | 2`, 1);
// no error
checkTsType(`'y' | 'n'`, 'foo');
// throw exception complaining wrong string value
checkTsType(`1 | 2`, 3);
// throw exception complaining wrong number value

checkTsType(`{
    UserId: string,
    Contact: {
      Method: 'telegram'
    } & ({ UserId: string } | { Tel: string }) | {
      Method: 'Email',
      Email: string
    }
  }`,{
    UserId: 'Alice',
    Contact: {
      Method: 'telegram',
      UserId: 'alice',
    },
  });
// no error
checkTsType(`{
    UserId: string,
    Contact: {
      Method: 'telegram'
    } & ({ UserId: string } | { Tel: string }) | {
      Method: 'Email',
      Email: string
    }
  }`,{
    UserId: 'Alice',
    Contact: {
      Method: 'Email',
      Email_: 'alice@domain.com',
    },
  });
// throw exception complaining missing field 'Email' (if the field is given, then will complain extra field 'Email_')