使用 TypeScript 和 Chai 的强类型深度相等断言
Strongly typed deep equal assertion with TypeScript and Chai
我有一个 TypeScript 函数 returns 一个类型 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',
});
})
当我更改 Foo
界面时,我的 getFoo()
函数产生 TypeScript 错误:
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',
};
}
但是,我的 Mocha 测试没有触发编译时错误!
是否有一种类型安全的方法expect().to.deep.equal()
?类似于:
// 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()
不在 equal
的类型定义中,它们是有意 any
的,因为它是为 运行时 检查而设计的。
但是在外部很容易做到:
const expected: Foo = {
bar: 'hello',
baz: 'world',
};
expect(getFoo()).to.deep.equal(expected);
我有一个 TypeScript 函数 returns 一个类型 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',
});
})
当我更改 Foo
界面时,我的 getFoo()
函数产生 TypeScript 错误:
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',
};
}
但是,我的 Mocha 测试没有触发编译时错误!
是否有一种类型安全的方法expect().to.deep.equal()
?类似于:
// 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()
不在 equal
的类型定义中,它们是有意 any
的,因为它是为 运行时 检查而设计的。
但是在外部很容易做到:
const expected: Foo = {
bar: 'hello',
baz: 'world',
};
expect(getFoo()).to.deep.equal(expected);