Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strongly typed deep equal assertion with TypeScript and Chai

I have a TypeScript function that returns a type Foo:

interface Foo {
  bar: string;
  baz: string;
}

function getFoo(): Foo {
  return {
    bar: 'hello',
    baz: 'world',
  };
}

// Chai Assertion
it('Should return a Foo', () => {
  expect(getFoo()).to.deep.equal({
    bar: 'hello',
    baz: 'world',
  });
})

When I change the Foo interface, my getFoo() function produces a TypeScript error:

interface Foo {
  bar: number;  // change these to numbers instead
  baz: number;
}

function getFoo(): Foo {
  // Compile time error! Numbers aren't strings!
  return {
    bar: 'hello',
    baz: 'world',
  };
}

However, my Mocha test does not trigger a compile time error!

Is there a type-safe way of doing expect().to.deep.equal()? Something like:

// Strawman for how I'd like to do type-safety for deep equality assertions,
// though this generic signature still seems unnecessary?
expect<Foo>(getFoo()).to.deep.equal({
  bar: 'hello',
  baz: 'world',
});
like image 558
Danny Delott Avatar asked Jan 30 '26 18:01

Danny Delott


1 Answers

Is there a type-safe way of doing expect().to.deep.equal()

Not in the type definitions of equal which are intentionally any as it is designed for runtime checking.

However easy to do externally:

const expected: Foo = {
  bar: 'hello',
  baz: 'world',
};
expect(getFoo()).to.deep.equal(expected);
like image 105
basarat Avatar answered Feb 02 '26 06:02

basarat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!