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',
});
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With