Skip to content

type narrowing for common testing patterns #9693

@rkirov

Description

@rkirov

When using 'strictNullChecks' with common testing libraries (jasmine, chai), one cannot easily express the intent that below a expect(result).toNotBeNull(); statement the object is non-null. The only solution that comes to mind is pervasive use of type assertion operator (!). Consider:

interface I {
  a: string;
  b: string;
  c: string;
}

declare function fnToTest(i: string): I|null;

function test() {
  let result: I|null = fnToTest('input');
  expect(result).toNotBeNull();
  expect(result!.a).toBe('foo');
  expect(result!.b).toBe('bar');
  expect(result!.c).toBe('buz');
}

I attempted to model the type of expect and toNotBeNull as:

interface Tos<T> {
  toBe(exp: T): void;
  toNotBeNull(): never;  // if T is null
  toNotBeNull(): void;   // if T is not null
}

declare function expect<T>(t: T): Tos<T>;

But I can't tell the type system to use a different function overload based on type of the type variable T (left in comments). Even if that was possible, I am also not sure if narrowing would propagate based on the never type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions