or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-types.mdbasic-types.mdfunctions.mdindex.mdobjects.mdtype-equality.md
tile.json

tessl/npm-expect-type

Compile-time tests for types to make sure types don't regress into being overly permissive as changes go in over time.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/expect-type@1.2.x

To install, run

npx @tessl/cli install tessl/npm-expect-type@1.2.0

index.mddocs/

expect-type

expect-type is a TypeScript library for compile-time type testing that provides Jest-inspired fluent API for making assertions about TypeScript types. It enables developers to write type-safe tests that verify type relationships, check for specific types, and validate complex type structures without runtime overhead.

Package Information

  • Package Name: expect-type
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install expect-type --save-dev

Core Imports

import { expectTypeOf } from "expect-type";

For CommonJS:

const { expectTypeOf } = require("expect-type");

Basic Usage

import { expectTypeOf } from "expect-type";

// Basic type equality checks
expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>();

// Check type extensions
expectTypeOf("hello").toExtend<string>();

// Check specific types
expectTypeOf(42).toBeNumber();
expectTypeOf("text").toBeString();

// Use .not to invert assertions
expectTypeOf({ a: 1 }).not.toEqualTypeOf<{ b: number }>();

// Function type checks
const fn = (x: number) => x * 2;
expectTypeOf(fn).parameter(0).toBeNumber();
expectTypeOf(fn).returns.toBeNumber();

Architecture

expect-type is built around several key components:

  • Core Function: expectTypeOf() as the main entry point for all type assertions
  • Fluent Interface: Chainable methods providing intuitive type checking syntax
  • Type Assertion Methods: Built-in checkers for primitive types, objects, functions, and complex structures
  • Type Transformers: Methods like .parameter(), .returns, .resolves for accessing nested types
  • Negation Support: .not property for inverting any assertion
  • Intersection Handling: .branded property for strict equality checks on intersection types

Capabilities

Type Equality and Matching

Core functionality for checking strict type equality and flexible type matching patterns.

function expectTypeOf<Actual>(actual: Actual): ExpectTypeOf<Actual, {positive: true; branded: false}>;
function expectTypeOf<Actual>(): ExpectTypeOf<Actual, {positive: true; branded: false}>;

Type Equality and Matching

Basic Type Checking

Fundamental type checking methods for JavaScript primitive types and common structures.

interface BaseExpectTypeOf<Actual, Options extends {positive: boolean}> {
  toBeAny: Scolder<ExpectAny<Actual>, Options>;
  toBeUnknown: Scolder<ExpectUnknown<Actual>, Options>;
  toBeNever: Scolder<ExpectNever<Actual>, Options>;
  toBeFunction: Scolder<ExpectFunction<Actual>, Options>;
  toBeObject: Scolder<ExpectObject<Actual>, Options>;
  toBeArray: Scolder<ExpectArray<Actual>, Options>;
  toBeNumber: Scolder<ExpectNumber<Actual>, Options>;
  toBeString: Scolder<ExpectString<Actual>, Options>;
  toBeBoolean: Scolder<ExpectBoolean<Actual>, Options>;
  toBeVoid: Scolder<ExpectVoid<Actual>, Options>;
  toBeSymbol: Scolder<ExpectSymbol<Actual>, Options>;
  toBeNull: Scolder<ExpectNull<Actual>, Options>;
  toBeUndefined: Scolder<ExpectUndefined<Actual>, Options>;
  toBeNullable: Scolder<ExpectNullable<Actual>, Options>;
  toBeBigInt: Scolder<ExpectBigInt<Actual>, Options>;
}

Basic Type Checking

Function Type Analysis

Comprehensive function type checking including parameters, return types, overloads, and callability.

interface BaseExpectTypeOf<Actual, Options extends {positive: boolean}> {
  toBeCallableWith<Args extends OverloadParameters<Actual>>(...args: Args): ExpectTypeOf<OverloadsNarrowedByParameters<Actual, Args>, Options>;
  toBeConstructibleWith<Args extends ConstructorOverloadParameters<Actual>>(...args: Args): boolean;
  parameter<Index extends number>(index: Index): ExpectTypeOf<OverloadParameters<Actual>[Index], Options>;
  parameters: ExpectTypeOf<OverloadParameters<Actual>, Options>;
  constructorParameters: ExpectTypeOf<ConstructorOverloadParameters<Actual>, Options>;
  thisParameter: ExpectTypeOf<ThisParameterType<Actual>, Options>;
  returns: ExpectTypeOf<OverloadReturnTypes<Actual>, Options>;
}

Function Type Analysis

Object and Property Testing

Object structure validation, property checking, and type manipulation utilities.

interface PositiveExpectTypeOf<Actual> {
  toHaveProperty<KeyType extends keyof Actual>(key: KeyType): PositiveExpectTypeOf<Actual[KeyType]>;
  pick<KeyToPick extends keyof Actual>(keyToPick?: KeyToPick): ExpectTypeOf<Pick<Actual, KeyToPick>, Options>;
  omit<KeyToOmit extends keyof Actual | (PropertyKey & Record<never, never>)>(keyToOmit?: KeyToOmit): ExpectTypeOf<Omit<Actual, KeyToOmit>, Options>;
}

Object and Property Testing

Advanced Type Operations

Complex type manipulation including union/intersection handling, type extraction, and generic transformations.

interface BaseExpectTypeOf<Actual, Options extends {positive: boolean}> {
  extract<V>(v?: V): ExpectTypeOf<Extract<Actual, V>, Options>;
  exclude<V>(v?: V): ExpectTypeOf<Exclude<Actual, V>, Options>;
  map<T>(fn: (value: Actual) => T): ExpectTypeOf<T, Options>;
  resolves: ExpectTypeOf<ResolvedType, Options>; // where Actual extends PromiseLike<ResolvedType>
  items: ExpectTypeOf<ItemType, Options>; // where Actual extends ArrayLike<ItemType>
  guards: ExpectTypeOf<GuardedType, Options>; // where Actual is type guard function
  asserts: ExpectTypeOf<AssertedType, Options>; // where Actual is assertion function
  instance: ExpectTypeOf<InstanceType, Options>; // where Actual is constructor
}

Advanced Type Operations

Utility Types (Legacy/Backcompat)

The package also exports numerous utility types for advanced type manipulation, primarily for backward compatibility with older versions. These are exported for historical reasons and may be removed in future major versions. New code should prefer the primary expectTypeOf API.

// Boolean operations on types
type Not<T extends boolean>;
type Or<Types extends boolean[]>;
type And<Types extends boolean[]>;
type Eq<Left extends boolean, Right extends boolean>;
type Xor<Types extends [boolean, boolean]>;

// Type checking utilities
type IsNever<T>;
type IsAny<T>;
type IsUnknown<T>;
type IsUnion<T>;
type IsTuple<T>;

// Type relationships
type Extends<Left, Right>;
type MutuallyExtends<Left, Right>;
type StrictEqualUsingTSInternalIdenticalToOperator<L, R>;

// Object property utilities
type UsefulKeys<T>;
type RequiredKeys<T>;
type OptionalKeys<T>;
type ReadonlyKeys<T>;
type DeepPickMatchingProps<Left, Right>;

// Union/tuple transformations
type UnionToIntersection<Union>;
type UnionToTuple<Union>;

// Function overload utilities
type OverloadParameters<FunctionType>;
type OverloadReturnTypes<FunctionType>;
type ConstructorOverloadParameters<ConstructorType>;

Types

// Helper types
type Scolder<Expecter, Options> = Options['positive'] extends true ? Expecter : boolean;
type MismatchArgs<ActualResult, ExpectedResult> = ActualResult extends ExpectedResult ? [] : [never];
type AValue = object & { __avalue: never }; // Special type for value matching in toEqualTypeOf overloads

// Core interfaces
interface PositiveExpectTypeOf<Actual> extends BaseExpectTypeOf<Actual, {positive: true; branded: false}> {
  toMatchObjectType<Expected>(...MISMATCH: MismatchArgs): true;
  toExtend<Expected>(...MISMATCH: MismatchArgs): true;
  toEqualTypeOf<Expected>(): true;
  toEqualTypeOf<Expected>(value: Expected): true;
  toHaveProperty<KeyType extends keyof Actual>(key: KeyType): PositiveExpectTypeOf<Actual[KeyType]>;
  not: NegativeExpectTypeOf<Actual>;
  branded: { toEqualTypeOf<Expected>(...MISMATCH: MismatchArgs): true };
}

interface NegativeExpectTypeOf<Actual> extends BaseExpectTypeOf<Actual, {positive: false}> {
  toMatchObjectType<Expected>(...MISMATCH: MismatchArgs): true;
  toExtend<Expected>(...MISMATCH: MismatchArgs): true;
  toEqualTypeOf<Expected>(): true;
  toEqualTypeOf<Expected>(value: Expected): true;
  toHaveProperty<KeyType extends string | number | symbol>(key: KeyType): true;
}

// Main type
type ExpectTypeOf<Actual, Options extends {positive: boolean}> = 
  Options['positive'] extends true 
    ? PositiveExpectTypeOf<Actual> 
    : NegativeExpectTypeOf<Actual>;

// Function type
type _ExpectTypeOf = {
  <Actual>(actual: Actual): ExpectTypeOf<Actual, {positive: true; branded: false}>;
  <Actual>(): ExpectTypeOf<Actual, {positive: true; branded: false}>;
};

Error Messages and Debugging

expect-type provides informative error messages when type assertions fail:

  • Type Mismatch: ExpectString<number> indicates you passed a number but expected a string
  • Property Missing: ExpectHaveProperty<'missing', SomeType> shows which property was expected but not found
  • Function Call: ExpectCallableWith<[string], FunctionType> shows expected vs actual parameter types
  • Generic Issues: Complex generic error messages include detailed type information for debugging

For better error messages, prefer generic type argument syntax (toEqualTypeOf<Type>()) over value inference when possible.