Utility TypeScript @ 2.0.0-beta.5
    Preparing search index...

    Namespace Test

    Utility types for unit testing TypeScript types.

    Types derived from and inspired by MichiganTypeScript/type-testing (GitHub) and Testing Types in TypeScript by Adam Rackis.

    0.1.0

    import { Test } from '@maddimathon/utility-typescript/types';
    

    Your type tests should probably be in the same file as your Javascript tests (and not in your production code where those objects are defined). For this example, imagine we imported this function to test.

    declare function toTest( param: boolean ): boolean;
    declare function toTest( param: string ): string;
    declare function toTest( param: boolean | string ): boolean | string;

    These values should also be tested by Jest/etc. for their values — and though this example is just looking at type testing, this lets us test the inferred return types at the same time.

    const testResults = {
    bool: toTest( true ),
    string: toTest( 'string' ),
    either: toTest( 'unk' as boolean | string ),
    };

    Here’s how I would test these types. Add two types to Exactly to test that these types match. In rare cases you might use Satisfies.

    Wrap your tests in either Expect or ExpectNot — if any of your tests fail, this is what will cause an error.

    // (export does nothing but avoid errors since these files don't go to prod!)
    export type T_toTest = [

    // testing the general return
    Test.Expect<Test.Exactly<ReturnType<typeof toTest>, boolean | string>>,

    // testing the override results
    Test.Expect<Test.Exactly<typeof testResults.bool, boolean>>,
    Test.Expect<Test.Exactly<typeof testResults.string, string>>,
    Test.Expect<Test.Exactly<typeof testResults.either, boolean | string>>,

    // testing what should fail is also useful
    Test.ExpectNot<Test.Exactly<typeof testResults.bool, string>>,
    Test.ExpectNot<Test.Exactly<typeof testResults.bool, boolean | string>>,
    Test.ExpectNot<Test.Exactly<typeof testResults.string, boolean>>,
    Test.ExpectNot<Test.Exactly<typeof testResults.string, boolean | string>>,
    Test.ExpectNot<Test.Exactly<typeof testResults.either, any>>,
    Test.ExpectNot<Test.Exactly<typeof testResults.either, boolean>>,
    Test.ExpectNot<Test.Exactly<typeof testResults.either, string>>,
    ];

    Type Aliases

    Exactly

    Tests if two types are exactly the same shape.

    Expect

    Demands the parameter evaluate to true.

    ExpectNot

    Demands the parameter evaluate to false. Inverse of Expect.

    IsArray

    Tests if a type is a valid array.

    Satisfies

    Tests if a given type would satisfy a given supertype.

    Equivalent

    Tests if the provided arguments resolve to equivalent TypeScript values.