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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.