Options
All
  • Public
  • Public/Protected
  • All
Menu

External module "index"

Index

Functions

assertNever

  • assertNever(_suspect: never): void
  • This function is no-op, but it is useful to check whether you have handled all the cases and some code path is unreachable.

    remarks

    TypeScript compiler will issue an error if you forward a value not of never type to this function.

    import * as Vts from 'vee-type-safe';
    const enum Enum {
        A, B, C
    }
    function fn(en: Enum) {
        switch (en) {
            case Enum.A: {  return; }
            case Enum.B: {  return; }
            default: {
                Vts.assertNever(en); // compile Error, en is of type Enum.C
            }
        }
    }
    //-------------
    const num = 23;
    if (typeof num !== 'number'){
        Vts.assertNever(num); // no error, this code is unreachable
        // num is of type never here
    }

    Parameters

    • _suspect: never

    Returns void

conforms

  • conforms<TTypeDescr>(suspect: unknown, typeDescr: TTypeDescr): boolean
  • Determines whether the specified suspect type satisfies the restriction of the given type description (TD).

    remarks
    import * as Vts from 'vee-type-safe';
    
    Vts.conforms(
    {
           prop: 'lala',
           tel:  '8800-555-35-35'
           prop2: true,
           obj: {
               obj: [23, false]
           },
           someIDontCareProperty: null // excess properties are ok
    },
    {
           prop: 'string',
           tel:  /\d{4}-\d{3}-\d{2}-\d{2}/, // claims a string of given format
           prop2: 'boolean',
           obj: {
               obj: ['number', 'boolean'] // claims a fixed length tuple
           }
    }); // true
    
    Vts.conforms(
    {
         arr: ['array', null, 'of any type', 8888 ],
         strArr: ['Pinkie', 'Promise', 'some', 'strings'],
         oneOf: 2,
         custom: 43
    },
    {
         arr: [],                              // claims an array of any type
         strArr: ['string'],                   // claims an array of any length
         oneOf: new Set(['boolean', 'number']),// claims to be one of these types
         custom: isOddNumber                   // custom type predicate function
    }); // true
    
    function isOddNumber(suspect: unknown): suspect is number {
        return typeof suspect === 'number' && suspect % 2;
    }
    
    // Type argument:
    interface Human {
        name: string;
        id:   number;
    }
    const HumanTD: Vts.TypeDescription<Human>  = {
        name: 'string',  // using Vts.TypeDescription<T> gives you better typing
        id:   'number'
    };
    function tryUseHuman(maybeHuman: unknown) {
        if (conforms<Human>(maybeHuman, HumanTD)) {
            // maybeHuman is of type Human here
            maybeHuman.name;
            maybeHuman.id;
        }
    }
    

    Type parameters

    Parameters

    • suspect: unknown

      Entity of unknown type to be tested for conformance according to TD.

    • typeDescr: TTypeDescr

      If it is a basic JavaScript typename string (should satisfy typeof operator domain definition), then function returns typeof suspect === typeDescr. If it is a RegExp, then returns typeof suspect === 'string' && typeDescr.test(suspect). Else if it is a Set, returns true if suspect conforms to at least one of the given TDs in Set. Else if it is an Array and it consists of one item, returns true if suspect is Array and each of its items conforms to the given TD at typeDescr[0]. Else if it is an Array and it consists of more than one item, returns true if suspect is Array and suspect.length === typeDescr.length and each suspect[i] conforms to typeDescr[i] type description. Else if it is an empty Array, returns true if suspet is Array of any type. Else if it is an object, returns true if suspect is an object and each typeDescr[key] is a TD for suspect[key]. (Excess properties in suspect do not matter). Else if it is a TypePredicate, then returns typeDescr(suspect). Else returns false.

    Returns boolean

defaultIfNotConforms

  • defaultIfNotConforms<TTarget>(typeDescr: TypeDescription<TTarget>, suspect: unknown, defaultVal: TTarget): TTarget
  • Checks whether suspect conforms to the given type description and returns it if yes, otherwise returns the default value.

    Type parameters

    • TTarget

    Parameters

    • typeDescr: TypeDescription<TTarget>

      Type description suspect may conform to, defaultVal MUST conform to this TD.

    • suspect: unknown

      Value of unknown type to provide default value for.

    • defaultVal: TTarget

      Value that conforms to typeDescr TD that is returned by this function if !conforms(suspect, typeDescr).

    Returns TTarget

duckMismatch

  • Same as mismatch(suspect, typeDescr) but allows suspect object with excess properties to pass the match.

    remarks
    import * as Vts from 'vee-type-safe';
    
    Vts.duckMismatch(
        { name: 'Ihor', somePropertyIDontCareAbout: 42 },
        { name: 'string' }
    ); // returns null as suspect is allowed to have excess properties
    
    const untrustedJson = {
        client: 'John Doe',
        walletNumber: null,
    };
    const ExpectedJsonTD: Vts.TypeDescription<typeof untrustedJson> = {
        client: 'string',
        walletNumber: /\d{16}/ // implies a string of the given format
    };
    
    const mismatchInfo = Vts.duckMismatch(untrustedJson, ExpectedJsonTD);
    if (mismatchInfo) {
        throw new Vts.TypeMismatchError(mismatchInfo);
    }
    // or you could use `Vts.ensureDuckMatch(untrustedJson, ExpectedJsonTD)`
    // which does the same thing.
    // ...
    // process validated client here

    Parameters

    • suspect: unknown

      Value of unknown type to be tested for conformance to typeDescr.

    • typeDescr: TypeDescription

      TypeDescription that describes limitations that must be applied to suspect to pass the match (see conforms() for more info about the structure of TypeDescription).

    Returns null | MismatchInfo

ensureDuckMatch

  • This function returns nothing. It throws TypeMismatchError if its suspect failed to match to the given typeDescr by executing duckMismatch(suspect, typeDescr).

    Parameters

    Returns void

ensureMatch

  • This function returns nothing. It throws TypeMismatchError if its suspect failed to match to the given typeDescr by executing mismatch(suspect, typeDescr).

    Parameters

    Returns void

exactlyConforms

  • exactlyConforms<TTypeDescr>(suspect: unknown, typeDescr: TTypeDescr): boolean
  • Same as conforms(), but returns false for suspect object that has excess properties (those, that are not present in type description object).

    remarks
    import * as Vts from 'vee-type-safe';
    Vts.conforms(23, 'number') === Vts.exactlyConforms(23, 'number');
    const suspect = {
        listedInt: 7,
        listedStr: 'readme',
        unlistedProp: ['some', 'excess', 'prop', 'value']
    }
    // notice that if you had used Vts.TypeDescription<typeof suspect> type here,
    // you would have got error squiggles, that td lacks 'unlistedProp' property.
    const td: Vts.TypeDescription = {
        listedInt: Vts.isPositiveInteger,
        listedStr: 'string'
    }
    Vts.conforms(suspect, td) === true;
    Vts.exactlyConforms(suspect, td) === false;

    Type parameters

    Parameters

    • suspect: unknown

      Entity of unknown type to be tested for conformance according to TD.

    • typeDescr: TTypeDescr

      TypeDescription that describes limitations that must be applied to suspect to pass the match (see conforms() for more info about the structure of TypeDescription).

    Returns boolean

makeTdWithOptionalProps

  • Returns a new TypeDescrObjMap (which is assignable to TypeDescription) object that is composed of typeDescr properties wrapped as

     result[propName] = optional(typeDescr[propName])

    for each propName in typeDescr own property names.

    Type parameters

    • TTD: TypeDescrObject

      Type of TD object, i.e an object with values of TypeDescription type.

    Parameters

    • typeDescr: TTD

      Object to make new TypeDescrObjMap with all optional properties from.

    Returns BasicObjectMap<keyof TTD, ReturnType<optional>>

mismatch

  • Returns a MismatchInfo object that stores an information about type incompatability for the given typeDescr.

    remarks

    MismatchInfo stores information about why and where suspect's invalid property is. If exactlyConforms(suspect, typeDescr) this function returns null. This is a powerful tool to generate useful error messages while validating value shape type. Note: this function doesn't let pass the match for suspect that has properties not listed in typeDescr which differentiates it from duckMismatch().

      import * as Vts from 'vee-type-safe';
      const untrustedJson = {}; // some value
      const ExpectedJsonTD: Vts.TypeDescription = {}; //some type description
      const dbDocument = {}; // some NoSQL database document
    
      const mismatchInfo = Vts.mismatch(untrustedJson, ExpectedJsonTD);
      if (mismatchInfo) {
          console.log(
              mismatchInfo.path,
              mismatchInfo.actualValue,
              mismatchInfo.expectedTd
          );
          // logs human readable path to invalid property
          console.log(mismatchInfo.pathString());
    
          // `mismatchInfo.toErrorString()` generates human readable error message
          throw new Vts.TypeMismatchError(mismatchInfo);
      }
      // now you may safely assign untrustedJson to dbDocument:
      dbDocument = Object.assign(dbDocument, untrustedJson);

    Parameters

    • suspect: unknown

      Value of unknown type to be tested for conformance to typeDescr.

    • typeDescr: TypeDescription

      TypeDescription that describes limitations that must be applied to suspect to pass the match (see conforms() for more info about the structure of TypeDescription).

    Returns null | MismatchInfo

reinterpret

  • reinterpret<T>(target: any): T
  • C++ style operator, a syntactic sugar for writing casts like value as any as T when a simple value as T cast cannot be performed. Use it with caution!

    remarks

    This function is actually noop at runtime, all it does, it suppresses 'inability to cast' tsc error. It's better to use this function rather than value as any as T cast, because it amplifies your attention to such uneven places in code and it may be easier to do a Ctrl + F search for these.

    Type parameters

    • T

    Parameters

    • target: any

      value to cast by any means to T.

    Returns T

take

  • take<TSourceObject, TPropNames>(sourceObject: TSourceObject, propertyNames: TPropNames): Take<TSourceObject, TPropNames>
  • Takes given properties from the object and returns them as a new object.

    remarks

    This function will be useful when serializing your objects as data holders using generic JSON.stringify() and you don't want any excess properties to be exposed to the serialized representation.

    import * as Vts from 'vee-type-safe';
    const userDocument = {
        _id: 'someid85',
        name: 'Kuzya',
        secretInfo: 42
    };
    JSON.stringify(userDocument);
    // {_id:"someid85",name:"Kuzya",secretInfo:42}
    JSON.stringify(take(userDocument, ['_id', 'name']));
    // {_id:"someid85",name:"Kuzya"}

    Type parameters

    Parameters

    • sourceObject: TSourceObject

      Source object to take data from.

    • propertyNames: TPropNames

      Array of property names to include to the returend object.

    Returns Take<TSourceObject, TPropNames>

    New object that is a shallow copy of sourceObject with the properties given as propertyNames array.

takeFromKeys

  • takeFromKeys<TKeysObject, TSourceObject>(sourceObject: TSourceObject, keysObj: TKeysObject): object
  • The same as take(sourceObject, Object.getOwnPropertyNames(keysObject)), but with stronger typing.

    Type parameters

    Parameters

    • sourceObject: TSourceObject
    • keysObj: TKeysObject

    Returns object

typeAssert

  • typeAssert<T>(_target: any): boolean
  • TypeScript type guard that always returns true.

    remarks

    You may use it in an if statement to assert the proper type in the following code execution path.

    import * as Vts from 'vee-type-safe';
    const enum SomeEnum {
        A = 0, B, C
    }
    const numb: number = 2;
    if (!Vts.typeAssert<SomeEnum>(numb)) { return; }
    numb; // deduced type is SomeEnum

    Type parameters

    • T

    Parameters

    • _target: any

      Target value, to make type assertion of.

    Returns boolean

Generated using TypeDoc